unit_3_PHP[1]
unit_3_PHP[1]
PHP string is a sequence of characters such as letters, numbers, or symbols, that are enclosed in
quotes (either single quotes or double quotes) i.e., used to store and manipulate text. PHP
supports only 256-character set and so that it does not offer native Unicode support. There are
4 ways to specify a string literal in PHP.
1. Single Quoted
2. Double Quoted
3. Heredoc Syntax
4. Nowdoc Syntax (Since PHP 5.3)
1. Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to
specify string in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a literal
backslash (\) use double backslash (\\). All the other instances with backslash such as \r or \n,
will be output same as they specified instead of having any special meaning.
Example:
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?> Execute Now
Output: Hello text within single quote
We can store multiple line text, special characters, and escape sequences in a single-quoted
PHP string.
Example:
1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?> Execute Now
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
Example:
1. <?php
2. $num1=10;
3. $str1='trying variable $num1';
4. $str2='trying backslash n and backslash t inside single quoted string \n \t';
5. $str3='Using single quote \'my quote\' and \\backslash';
6. echo "$str1 <br/> $str2 <br/> $str3";
7. ?>
Execute Now
Output:
trying variable $num1
trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash
Note: In single quoted PHP strings, most escape sequences and variables will not be
interpreted. But, we can use single quote through \' and backslash through \\ inside single
quoted PHP strings.
2. Double Quoted:
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.
Example
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Execute Now
Output:
Hello text within double quote
Now, you can't use double quote directly inside double quoted string.
Example:
1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?> Execute Now
Output:
Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on line
2
We can store multiple line text, special characters and escape sequences in a double quoted
PHP string.
Example:
1. <?php
2. $str1="Hello text
3. multiple line
4. text within double quoted string";
5. $str2="Using double \"quote\" with backslash inside double quoted string";
6. $str3="Using escape sequences \n in double quoted string";
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Execute Now
Output:
Hello text multiple line text within double quoted string
Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string
3. Heredoc
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.
Valid Example
1. <?php
2. $str = <<<Demo
3. It is a valid example
4. Demo; //Valid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
Output:
It is a valid example
Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, which
means identifier must not be indented. The identifier must begin from the new line.
1. <?php
2. $str = <<<Demo
3. It is Invalid example
4. Demo; //Invalid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
This code will generate an error.
Output: Parse error: Invalid body indentation level (expecting an indentation level of at least 1)
in C:\xampp\htdocs\php practical\Heredoc.php on line 3
Heredoc is similar to the double-quoted string, without the double quote, means that quote in
a heredoc are not required. It can also print the variable's value.
Example
1. <?php
2. $city = 'Delhi';
3. $str = <<<DEMO
4. Hello! My name is John, and I live in $city.
5. DEMO;
6. echo $str;
7. ?>
Output:
Hello! My name is John, and I live in Delhi.
Example: We can add multiple lines of text here between heredoc syntax.
1. <?php
2. $str = <<<DEMO
3. It is the example
4. of multiple
5. lines of text.
6. DEMO;
7. echo $str;
8. echo '</br>';
9. echo <<<DEMO // Here we are not storing string content in variable str.
10. It is the example
11. of multiple
12. lines of text.
13. DEMO;
14. ?>
Output:
It is the example of multiple lines of text.
It is the example of multiple lines of text.
4. Nowdoc:
Nowdoc is similar to the heredoc, but in nowdoc 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'. Nowdoc follows the same rule as heredocs.
1. <?php
2. $str = <<<'DEMO'
3. Welcome to TPointTech.
4. Learn with newdoc example.
5. DEMO;
6. echo $str;
7. echo '</br>';
8. echo <<< 'Demo' // Here we are not storing string content in variable str.
9. Welcome to TPointTech.
10. Learn with newdoc example.
11. Demo;
12. ?>
Output:
Welcome to TPointTech. Learn with newdoc example.
Welcome to TPointTech. Learn with newdoc example.
Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, means
identifier must not be indented. The identifier must begin from the new line. It is also invalid in
newdoc same as heredoc.
1. <?php
2. $str = <<<'Demo'
3. It is Invalid example
4. Demo; //Invalid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>
This code will generate an error.
Output: Parse error: Invalid body indentation level (expecting an indentation level of at least 2)
in C:\xampp\htdocs\php practical\nowdoc.php on line 3
Replacing a String
PHP provides several functions to replace a string with another string:
1. str_replace() Replaces all occurrences of a substring with a new string.
$string = 'Hello, World!';
$new_string = str_replace('World', 'Universe', $string);
echo $new_string; // Output: Hello, Universe!
3. preg_replace() Replaces all occurrences of a substring with a new string, using regular
expressions.
$string = 'Hello, World!';
$new_string = preg_replace('/World/i', 'Universe', $string);
echo $new_string; // Output: Hello, Universe!
# Regular Expressions
Regular expressions (regex) are a powerful way to search and replace strings in PHP.
1. preg_match() Finds the first occurrence of a pattern in a string.
$string = 'Hello, World!';
$pattern = '/World/i';
preg_match($pattern, $string, $matches);
echo $matches[0]; // Output: World
String Padding:
PHP provides several functions to pad strings:
1. str_pad() Pads a string with a specified character.
$string = 'Hello';
$padded_string = str_pad($string, 10, '*');
// Output: Hello*****
2. str_repeat() Repeats a string a specified number of times.
$string = '*';
$repeated_string = str_repeat($string, 5);
// Output: *****
String Trimming:
PHP provides several functions to trim strings:
1. trim() Removes whitespace from the beginning and end of a string.
$string = ' Hello, World! ';
$trimmed_string = trim($string);
🔹 1. strlen()
Definition: Returns the length of a string (number of characters).
$str = "Hello PHP";
echo strlen($str); // Output: 9
🔹 2. strtoupper() / strtolower()
Definition: Converts a string to uppercase or lowercase.
echo strtoupper("hello"); // Output: HELLO
echo strtolower("WORLD"); // Output: world
🔹 3. ucfirst() / ucwords()
Definition:
ucfirst() capitalizes the first letter of a string.
ucwords() capitalizes the first letter of each word.
echo ucfirst("php is cool"); // Output: Php is cool
echo ucwords("php is cool"); // Output: Php Is Cool
🔹 5. strpos() / stripos()
Definition: Finds the position of the first occurrence of a substring.
strpos() is case-sensitive.
stripos() is case-insensitive.
echo strpos("Hello World", "World"); // Output: 6
echo stripos("Hello World", "world"); // Output: 6
🔹 6. str_replace() / str_ireplace()
Definition: Replaces all occurrences of a search string with a replacement string.
str_replace() is case-sensitive.
str_ireplace() is case-insensitive.
echo str_replace("PHP", "Java", "I love PHP"); // I love Java
🔹 7. substr()
Definition: Returns a portion of a string.
echo substr("Hello World world", 5, 8); // Output: World w
🔹 8. explode() / implode()
Definition:
explode() splits a string into an array.
implode() joins array elements into a string.
$str = "apple,banana,grape";
print_r(explode(",", $str)); // Output: Array ( [0] => apple [1] => banana [2] => grape )
🔹 9. strrev()
Definition: Reverses a string.
echo strrev("java"); // Output: avaj
🔹 11. number_format()
Definition: Formats a number with grouped thousands.
echo number_format(1234567.89, 2); // Output: 1,234,567.89
🔹 12. strchr() (alias of strstr())
Definition: Finds the first occurrence of a character in a string and returns the rest.
$email = "[email protected]";
echo strchr($email, "@"); // Output: "@example.com"
🔹 13. wordwrap()
Definition:
The wordwrap() function wraps a string to a given number of characters using a break character
(like a newline \n or <br> for HTML).
$text = "The quick brown fox jumps over the lazy dog.";
echo wordwrap($text, 15);
//Output: The quick brown
fox jumps over
the lazy dog.
🔹 14. str_repeat()
Definition: Repeats a string a specified number of times.
echo str_repeat("Hi ", 3); // Output: Hi Hi Hi
In PHP, regular expressions are strings composed of delimiters, a pattern and optional
modifiers.
$exp = "/Biyani/i";
In the example above, / is the delimiter, Biyani is the pattern that is being searched for, and i is
a modifier that makes the search case-insensitive.
The delimiter can be any character that is not a letter, number, backslash or space. The most
common delimiter is the forward slash (/), but when your pattern contains forward slashes it is
convenient to choose other delimiters such as # or ~.
PHP provides a variety of functions that allow you to use regular expressions.
The most common functions are:
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string,
which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced
with another string
1.preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
$str = "Visit Biyani";
$pattern = "/biyani/i";
echo preg_match($pattern, $str);//Output: 1
2. preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a
string.
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);//Output: 4
3. preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string with
another string.
Ex:-1. [^abc]
$txt = "Welcome";
$pattern = "/[^eo]/";
echo preg_match_all($pattern, $txt);// Output: 4
Ex:-2.
$txt = "Call 555-2368";
$pattern = "/[0-5]/";
echo preg_match_all($pattern, $txt);//Output: 5
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|
dog|fish
. Find any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find any digits
\D Find any non-digits
\s Find any whitespace character
\S Find any non-whitespace character
\w Find any alphabetical letter (a to Z) and digit (0 to 9)
\W Find any non-alphabetical and non-digit character
\b Find a match at the beginning of a word like this: \bWORD, or at
the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number
xxxx
Ex:-1. \d
$txt = "Biyani has been live since 1999";
$pattern = "/\d/";
echo preg_match_all($pattern, $txt);//Output: 3
Ex:-2. \b
$txt = "Hello World";
$pattern = "/\bHel/";
echo preg_replace($pattern, "#", $txt);//Output: #lo World
Quantifiers
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{3} Matches any string that contains a sequence of 3 n's
n{2,5} atches any string that contains a sequence of at least 2, but not
more that 5 n's
n{3,} Matches any string that contains a sequence of at least 3 n's
Ex:1. n{3}
$txt = "Biyani is goood";
$pattern = "/o{3}/";
echo preg_match_all($pattern, $txt);//Output: 1
Ex:2. n{3,}
$txt = “Biyani is goooooood";
$pattern = "/o{3,}/";
echo preg_match_all($pattern, $txt); //Output: 1