You are on page 1of 30

Web Programming

String:

Strings can be seen as a stream of characters. It is a sequence of letters, numbers, special characters and
arithmetic values or combination of all.
For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use
double backslash (\\).

Example: Single Quoted String

<?php
$str='Hello text within single quote'; echo $str;
?>

Output:
Hello text within single quote

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: multiline single quoted string

<?php
$str1='Hello text multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>

Output:
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string

3. String Manipulations And File Handling Centre for Distance and Online
Web Programming

Example : backslash n and backslash t inside single quoted string


<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
trying variable $num1
trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash

Double quote:
In PHP, we can specify string through enclosing text within double quote also. But escape sequences and
variables will be interpreted using double quote PHP strings.

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example : Double quoted string


<?php
$str="Hello text within double quote"; echo $str;
?>
Output:
Hello text within double quote
We can't use double quote directly inside double quoted string.

Example: interpreted variable

<?php
$num1=10;
echo "Number is: $num1";
?>
Output:
Number is: 10

3. String Manipulations And File Handling


Centre for Distance and Online
Education
Web Programming

Heredoc syntax
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is provided after this heredoc
<<< operator, and immediately a new line is started to write any text. To close the quotation, the string follows itself
and then again that same identifier is provided. That closing identifier must begin from the new line without any
whitespace or tab.
Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters and underscores, and
must start with an underscore or a non-digit character.

Example: Valid Example of Heredoc

<?php
$str = <<<Demo It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing identifier echo $str;
?>
Output:
It is a valid example

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Newdoc syntax (since PHP 5.3)


Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with three less than symbols
<<< followed by an identifier. But here identifier is enclosed in single-quote, e.g. <<<'EXP'. Newdoc follows the same
rule as heredocs. The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas
heredoc is a double-quoted string.

Example : Valid Example of Newdoc


<?php
$str = <<<'DEMO'
Welcome to PHP.
Learn with newdoc example.
DEMO;
echo $str; echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str. Welcome to PHP.
Learn with newdoc example.
Demo;
?>
Output: Welcome to PHP. Learn with newdoc example. Welcome to PHP. Learn with newdoc example.

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

STRING FUNCTIONS IN PHP

Function Name Use

chop() It removes whitespace or other cha racters from the right end of a string

chr() It is used to return a character from a specified ASCII value.

count_chars() It is used to return information about characters used in a string.

hex2bin() It is used to convert string of hexadecimal values to ASCII characters.

Lcfirst() It is used to convert the first character of a string to lowercase.

ltrim() It is used to remove whitespace from the left side of


a string.

md5() It is used to calculate the MD5 hash of a string.


md5_files() It is used to calculate MD5 hash of a file.

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

STRING FUNCTIONS IN PHP

Function Name Use


It is used to remove whitespace from the right side
rtrim() of a string.
strcasecmp() It is used to compare two strings.

strchr() It is used to find the first occurrence of a string


inside another string.
strcmp() Binary safe string comparison (case-sensitive)

stripos() It is used to return the position of the first


occurrence of a string inside another string.
stristr() Case-insensitive strstr
strlen() It is used to return the length of a string.
strncmp() It is used to compare of the first n characters.

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

STRING FUNCTIONS IN PHP

Function Name Use

strpos() It is used to return the position of the first


occurrence of a string inside another string.
strrev() It is used to reverse a string.
strstr() Find the occurrence of a string.
strtok() Splits the string into smaller strings
strtolower() Convert the string in lowercase
strtoupper() Convert the strings in uppercase
ucfirst() Make the first character of the string to uppercase

ucwords() Make the first character o f each word in a string to


uppercase

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: strtoupper() function


<?php
$str="My name is Raj";
$str=strtoupper($str);
echo $str;
?>
Output:
MY NAME IS RAJ

Example: strtolower() function


<?php
$str="My name is Raj";
$str=strtolower ($str);
echo $str;
?>
Output:
My name is Raj

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: ucfirst() function


<?php
$str="my name is Raj";
$str=ucfirst($str);
echo $str;
?>
Output:
My name is Raj

Example: lcfirst() function


<?php
$str="MY name IS RAJ";
$str=lcfirst($str); echo $str;
?>

Output:
mY name IS RAJ

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: ucwords() function


<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str); echo $str;
?>
Output:
My Name Is Sonoo Jaiswal

Example: strrev() function


<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str); echo $str;
?>
Output:
lawsiaj oonoS si eman ym

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example : strlen() function


<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str); echo $str;
?>
Output:
24

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

DATE AND TIME IN PHP


The PHP Date() Function
The PHP date() function is used to format a date and/or a time. The PHP date() function formats a timestamp to a
more readable date and time.
Syntax
date(format,timestamp)

Where, format is Required parameter and Specifies the format of the timestamp.
timestamp is Optional and Specifies a timestamp. Default is the current date and time. A timestamp is a sequence of
characters, denoting the date and/or time at which a certain event occurred.

Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: formats today's date in three different ways


<html>
<body>
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>"; echo "Today is " . date("l");
?>
</body>
</html>

Output:
Today is 2020/09/17
Today is 2020.09.17
Today is 2020-09-17
Today is Thursday

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Get a Time
Here are some characters that are commonly used for times:
H - 24-hour format of an hour (00 to 23)
h - 12-hour format of an hour with leading zeros (01 to 12)
i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
a - Lowercase Ante meridiem and Post meridiem (am or pm) The example below outputs the current time in the
specified format:
Example: current time in the specified format
<html>
<body>
<?php
echo "The time is " . date("h:i:sa");
?>
</body>
</html>

Output: The time is 12:43:21pm

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Create a Date With mktime()


The PHP mktime() function returns the Unix timestamp for a date.

Syntax
mktime(hour, minute, second, month, day, year)

Example: mktime() function


<html>
<body>
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
</body>
</html>
Output:
Created date is 2014-08-12 11:14:54am

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Create a Date From a String With strtotime()


The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp.
Syntax
strtotime(time, now)

The example below creates a date and time from the strtotime() function:

Example : strtotime()
<html>
<body>
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
</body>
</html>

Output: Created date is 2014-04-15 10:30:00pm

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example : converting a string to a date


<html>
<body>
<?php
$d=strtotime("tomorrow");
echo "tomorrow is ", date("d-m-Y ", $d) . "<br>";

$d=strtotime("next Saturday");
echo "next Saturday is ",date("d-m-Y", $d) . "<br>";

$d=strtotime("+3 Months");
echo "date after 3 Months is ", date("d-m-Y", $d) . "<br>";
?>
</body>
</html>
Output:
tomorrow is 18-09-2020
next Saturday is 19-09-2020
date after 3 Months is 17-12-2020
3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

date/time functions in PHP

Function Description
checkdate() Validates a Gregorian date
date_add() Adds days, months, years, hours, minutes, and
seconds to a date
date_diff() Returns the difference between two dates
date_format() Returns a date formatted according to a
specified Format
date() Formats a local date and time
getdate() Returns date/time information of a timestamp or
the current local date/time
gettimeofday() Returns the current time
gmdate() Formats a GMT/UTC date and time
gmmktime() Returns the Unix timestamp for a GMT date

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

WORKING WITH FORMS IN PHP:

PHP Get Form

Get request is the default form request. The data passed through get request is visible on the URL browser so it is not
secured. You can send limited amount of data through get request.

//form1.html
<form action="welcome.php" method="get"> Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file
welcome.php

<?php
$name=$_GET["name"];//receiving name field value in $name variable echo "Welcome, $name";
?>

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

PHP Post Form

Post request is widely used to submit form that have large amount of data such as file upload, image upload, login
form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You can send large amount
of data through post request.
//form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td>
< i n p u t t y p e = " p a s s w o r d " name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file
login.php

<html>
<body>
<form action="welcome.php" method="post"> Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file
named "welcome.php". The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

FILE HANDLING IN PHP


PHP File System allows us to create file, read file line by line, read file character by character, write file, append
file, delete file and close file.

PHP Open File - fopen()


The PHP fopen() function is used to open a file.

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only . Erases the contents of the file or creates a new file if
It doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only . The existing data in file is preserved. File pointer s
tarts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already
Exists
r+
Open a file for read/write. File pointer starts at the beginning of the file
w+
Open a f ile for read/write . Erases the contents of the file or creates a new file
if
It doesn't exist. File pointer starts at the beginning of the file
a+
Open a file for read/write. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x+
Creates a new file for read/write. Returns FALSE and an error if file already
exists

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example:fopen()
<?php
$handle = fopen("D:\VNM\Files\file.txt", "r");
?>

PHP Close File - fclose()


The PHP fclose() function is used to close an open file pointer.
Syntax
fclose ( resource $handle )
Example: fclose()
<?php fclose($handle);
?>
PHP Read File - fread()
The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file size.
Syntax
string fread ( resource $handle , int $length )

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: fread()
<?php
$filename = "D:\VNM\Files\file.txt";
$handle = fopen($filename, "r");//open file in read mode
$contents = fread($handle, filesize($filename));//read file
echo $contents;//printing data of file
fclose($handle);//close file
?>
Output:
This is a Text File

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.
Syntax
string fgets ( resource $handle [, int $length ] )

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: fgets()
<?php
$fp = fopen("D:\VNM\Files\file.txt", "r");//open file in read mode echo fgets($fp);
fclose($fp);
?>
Output:
This is a Text File

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function, use !feof()
function inside the while loop.
Syntax
string fgetc ( resource $handle )
Example : fetc()
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) { echo fgetc($fp);}
fclose($fp);
?>
3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

PHPWrite File - fwrite()


The PHP fwrite() function is used to write content of the string into file.
Syntax
int fwrite ( resource $handle , string $string [, int $length ] )
Example : fwrite()
<?php
$fp = fopen('data.txt', 'w');//open file in write mode fwrite($fp, 'Hello ');
fwrite($fp, 'php file');
fclose($fp);
?>
Output: data.txt Hello php file

Example : Overwriting File


<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, Data over write);
fclose($fp);
?>

3. String Manipulations And File Handling Centre for Distance and Online
Education
Web Programming

Example: Append to File


<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
?>

PHP Delete File - unlink()


The PHP unlink() function is used to delete file.
Syntax : bool unlink ( string $filename [, resource $context ] )
Example: Delete File - unlink()
<?php
unlink('data.txt');
echo "File deleted successfully";
?>

3. String Manipulations And File Handling Centre for Distance and Online
Education

You might also like