0% found this document useful (0 votes)
15 views16 pages

unit_3_PHP[1]

The document provides an overview of PHP strings, detailing their types including single-quoted, double-quoted, heredoc, and nowdoc strings. It explains how to create and manipulate strings, including searching, replacing, and formatting them, along with examples of various string functions. Additionally, it covers string padding, trimming, and commonly used string functions in PHP.

Uploaded by

tanchukumawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views16 pages

unit_3_PHP[1]

The document provides an overview of PHP strings, detailing their types including single-quoted, double-quoted, heredoc, and nowdoc strings. It explains how to create and manipulate strings, including searching, replacing, and formatting them, along with examples of various string functions. Additionally, it covers string padding, trimming, and commonly used string functions in PHP.

Uploaded by

tanchukumawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit 3: PHP String

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.

Types of Strings 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.

Note: Nowdoc works as single quotes.


Example-1:

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

Searching and Replacing Strings in PHP:


# Searching for a String
PHP provides several functions to search for a string within another string:
1. strpos() Finds the position of the first occurrence of a substring.
$string = 'Hello, World! World';
$pos = strpos($string, 'World');
echo $pos; // Output: 7

2. strrpos() Finds the position of the last occurrence of a substring.


$string = 'Hello, World! World';
$pos = strrpos($string, 'World');
echo $pos; // Output: 14

3. stripos() Finds the position of the first occurrence of a substring, case-insensitive.


$string = 'Hello, World! World';
$pos = stripos($string, 'world');
echo $pos; // Output: 7

4. strripos() Finds the position of the last occurrence of a substring, case-insensitive.


$string = 'Hello, World! World';
$pos = strripos($string, 'world');
echo $pos; // Output: 14

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!

2. str_ireplace() Replaces all occurrences of a substring with a new string, case-insensitive.


$string = 'Hello, World!';
$new_string = str_ireplace('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

2. preg_replace() Replaces all occurrences of a pattern in a string with a new string.


$string = 'Hello, World!';
$pattern = '/World/i';
$new_string = preg_replace($pattern, 'Universe', $string);
echo $new_string; // Output: Hello, Universe!

Formatting Strings in PHP:


PHP provides several functions to format strings:
1. printf() Formats a string using a format specifier.
$name = 'John';
$age = 30;
printf('My name is %s and I am %d years old.', $name, $age);
// Output: My name is John and I am 30 years old.

2. sprintf() Returns a formatted string.


$name = 'John';
$age = 30;
$formatted_string = sprintf('My name is %s and I am %d years old.', $name, $age);
echo $formatted_string;
// Output: My name is John and I am 30 years old.

3. number_format() Formats a number with grouped thousands.


$number = 1234567.89;
$formatted_number = number_format($number, 2);
// Output: 1,234,567.89

4. date() Formats a date and time.


$date = date('Y-m-d H:i:s');
// Output: 2023-03-16 14:30:00

String Formatting Specifiers:


PHP provides several string formatting specifiers:
1. %s String specifier.
$name = 'John';
printf('My name is %s.', $name);

// Output: My name is John.


2. %d Integer specifier.
$age = 30;
printf('I am %d years old.', $age);
// Output: I am 30 years old.
3. %f Float specifier.
$pi = 3.14159;
printf('The value of pi is %f.', $pi);

// Output: The value of pi is 3.14159.


4. %b Binary specifier.
$number = 12;
printf('The binary representation of %d is %b.', $number, $number);

// Output: The binary representation of 12 is 1100.

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);

// Output: Hello, World!


2. ltrim() Removes whitespace from the beginning of a string.
$string = ' Hello, World!';
$trimmed_string = ltrim($string);

// Output: Hello, World!


3. rtrim() Removes whitespace from the end of a string.
$string = 'Hello, World! ';
$trimmed_string = rtrim($string);

// Output: Hello, World!


Of course! Here's a list of commonly used string functions in PHP with definitions and
examples to help you understand their purpose and usage.

PHP String Functions (String Related-Library Function)

🔹 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

🔹 4. trim() / ltrim() / rtrim()


Definition: Removes whitespace from both sides (or left/right side) of a string.
$str = " Hello ";
echo trim($str); // Output: "Hello"

🔹 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 )

$arr = ["one", "two"];


echo implode("-", $arr); // Output: one-two

🔹 9. strrev()
Definition: Reverses a string.
echo strrev("java"); // Output: avaj

🔹 10. strcmp() / strcasecmp()


Definition: Compares two strings.
 strcmp() is case-sensitive.
 strcasecmp() is case-insensitive.
echo strcmp("abc", "abc"); // 0 (equal)
echo strcasecmp("abc", "ABC"); // 0 (equal, ignoring case)

🔹 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

🔹 15. printf() / sprintf()


Definition: Outputs a formatted string.
printf("Price: $%.2f", 3.5); // Output: Price: $3.50

$str = sprintf("Score: %d", 99);


echo $str; // Output: Score: 99

PHP Regular Expression(Pattern Matching)


Regular expressions are commonly known as regex. These are nothing more than a pattern or a
sequence of characters, which describe a special search pattern as text string.
Regular expression allows you to search a specific string inside another string. Even we can
replace one string by another string and also split a string into multiple chunks. They use
arithmetic operators (+, -, ^) to create complex expressions.
By default, regular expressions are case sensitive.

Advantage and uses of Regular Expression


Regular expression is used almost everywhere in current application programming. Below some
advantages and uses of regular expressions are given:
1. Regular expression helps the programmers to validate text string.
2. It offers a powerful tool to analyze and search a pattern as well as to modify the text
string.
3. By using regexes functions, simple and easy solutions are provided to identify the
patterns.
4. Regexes are helpful for creating the HTML template system recognizing tags.
5. Regexes are widely used for browser detection, form validation, spam filtration, and
password strength checking.
6. It is helpful in user input validation testing like email address, mobile number, and IP
address.
7. It helps in highlighting the special keywords in file based upon the search result or input.
8. Metacharacters allow us to create more complex patterns.
You can create complex search patterns by applying some basic rules of regular expressions.
Many arithmetic operators (+, -, ^) are also used by regular expressions to create complex
patterns.
Syntax

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 ~.

Regular Expression Functions:

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.

$str = "Visit Microsoft!";


$pattern = "/microsoft/i";
echo preg_replace($pattern, "Biyani", $str);//Output: Visit Biyani

Regular Expression Modifiers

Modifiers can change how a search is performed.


Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for a match at the
beginning or end of a string will now match the beginning or end
of each line)
u Enables correct matching of UTF-8 encoded patterns

Regular Expression Patterns


Brackets are used to find a range of characters:
Expression Description
[abc] Find one or many of the characters inside the brackets
[^abc] Find any character NOT between the brackets
[a-z] Find any character alphabetically between two letters
[A-z] Find any character alphabetically between a specified upper-case letter
and a specified lower-case letter
[A-Z] Find any character alphabetically between two upper-case letters.
[123] Find one or many of the digits inside the brackets
[0-5] Find any digits between the two numbers
[0-9] Find any digits

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

You might also like