String in PHP
String in PHP
• Strings
• Strings in PHP are surrounded by either double quotation marks, or single
quotation marks.
• Example
<?php
echo "Hello";
echo 'Hello’;
?>
o/p
HelloHello
• Note
• There is a big different between double quotes and single quotes in PHP.
• Double quotes process special characters, single quotes does not.
• Double or Single Quotes?
• You can use double or single quotes, but you should be aware of the differences
between the two.
• Double quoted strings perform action on special characters.
• E.g. when there is a variable in the string, it returns the value of the variable:
• Example
• Double quoted string literals perform operations for special characters:
<?php
$x = “Everyone";
echo "Hello $x";
echo ‘Hello $x’;
?>
Hello Everyone
Hello $x
<?php
$x = “Everyone";
echo ‘Hello $x’;
?>
o/p Hello $x
• String Length
• The PHP strlen() function returns the length of a string.
• Example
• Return the length of the string "Hello world!":
echo strlen("Hello world!");
• Word Count
• The PHP str_word_count() function counts the number of words in a string.
• Example
• Count the number of word in the string "Hello world!":
echo str_word_count("Hello world!");
Search For Text Within a String
• The PHP strpos() function searches for a specific text within a string.
• If a match is found, the function returns the character position of the first match. If no
match is found, it will return FALSE.
• Example
• Search for the text "world" in the string "Hello world!":
echo strpos("Hello world!", "world");
Upper Case
• ExampleGet your own PHP Server
• The strtoupper() function returns the string in upper case:
• $x = "Hello World!";
echo strtoupper($x);
Lower Case
Example
The strtolower() function returns the string in lower case:
$x = "Hello World!";
echo strtolower($x);
Replace String
The PHP str_replace() function replaces some characters with some other characters in a string.
Example
Replace the text "World" with "Dolly":
$x = "Hello World!";
echo str_replace("World", "Dolly", $x);
• Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello World!":
$x = "Hello World!";
echo strrev($x);
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you
want to remove this space.
Example
The trim() removes any whitespace from the beginning or the end:
$x = " Hello World! ";
echo trim($x);
• Convert String into Array
The PHP explode() function splits a string into an array.
The first parameter of the explode() function represents the "separator". The "separator"
specifies where to split the string.
Note: The separator is required.
Example
Split the string into an array. Use the space character as separator:
$x = "Hello World!");
$y = explode(" ", $x);
//Use the print_r() function to display the result:
print_r($y);
/*
Result:
Array ( [0] => Hello [1] => World! )
*/
• String Concatenation
To concatenate, or combine, two strings you can use the . operator:
1) Example
Get your own PHP Server
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
2) An easier and better way is by using the power of double quotes.
By surrounding the two variables in double quotes with a white space between them, the
white space will also be present in the result:
Example
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
o/p Hello World
• Slicing
You can return a range of characters by using the substr() function.
Specify the start index and the number of characters you want to return.
ExampleGet your own PHP Server
Start the slice at index 6 and end the slice 5 positions later:
$x = "Hello World!";
Echo substr($x, 6, 5);
o/p World
Note The first character has index 0.
Slice to the End
By leaving out the length parameter, the range will go to the end:
Example
Start the slice at index 6 and go all the way to the end:
$x = "Hello World!";
echo substr($x, 6);
o/p World!
• Slice From the End
Use negative indexes to start the slice from the end of the string:
Example
Get the 3 characters, starting from the "o" in world (index -5):
$x = "Hello World!";
echo substr($x, -5, 3);
Note The last character has index -1.
o/p orl
Negative Length
Use negative length to specify how many characters to omit, starting from the end of the string:
Example
Get the characters starting from the "W" in "World" (index 5) and continue until 3 characters
from the end.
Should end up with "Wor":
$x = "Hello World!"; Hello World!
echo substr($x, 5, -3); 5
o/p Wor -3-2-1
• Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
Example
$x = "We are the so-called "Vikings" from the north.";
$x = "We are the so-called \"Vikings\" from the north.";
\r
<pre>
<?php
$x = "Hello\rWorld";
echo $x;
?>
</pre>
o/p
Hello
World
Code Result <?php
\’ Single Quote $x = "\x48\x65\x6c\x6c\x6f"; //Hexa value
echo $x;
\" Double Quote $x = "\110\145\154\154\157"; //octal value
echo $x;
\$ PHP variables $x = “\’Hello\’\nWorld"; //\n
echo $x;
\n New Line ?> ‘Hello’
\r Carriage Return o/p Hello
Hello
\t Tab Hello
\f Form Feed World
\ooo Octal value
\xhh Hex value
• 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.
• For Example
• Heredoc Syntax
• By using the syntax, we can display the HTML elements through PHP Script.
• Syntax
<<<name of string
//content
name of string
echo <<<EOT
Hello World.
Goodbye!
EOT;
// Output:-
// Hello World.
// Goodbye!
• The identifier for this heredoc is EOT. Remember we could have used any
alphanumeric identifier to mark the beginning and end of the string, e.g. MARK.
The opening identifier must always be proceeded by the <<< operator.
• Heredoc’s are equivalent to a double quoted string. That means any variables in
the string will get substituted for their respective values. We could rewrite the
double quoted string example above as a heredoc:-
echo <<<EOT
Hello $foo
Goodbye!
EOT;
// Output:-
// Hello bar
// Goodbye!
• Nowdoc’s are equivalent to a single quoted string. To denote a nowdoc we just
need to use single quotes around the opening identifier:-
echo <<<'EOT'
Hello $foo
Goodbye!
EOT;
// Output:-
// Hello $foo
// Goodbye!
The placement of the closing identifier is important. Prior to PHP 7.3 it had to
always be placed on a new line followed by a semi-colon and with no white-space
in front of it. So all the examples above would be valid. However, as of PHP 7.3
these rules have been relaxed a little.
• New Closing Identifier Rules
• As of PHP 7.3 the following is valid.
• If we use whitespace in front of the closing identifier then the same amount of whitespace will be deducted from the start of
each line of the string.
• // Valid from PHP 7.3
echo <<<EOT
SELECT * FROM `contacts`
WHERE `telephone` IS NOT NULL;
EOT;
• // Output:-
• // SELECT * FROM `contacts`
• // WHERE `telephone` IS NOT NULL;
• In this example, there are four spaces before the closing identifier EOT. This means four spaces will be removed from the
start of both lines of the string. As a result only the second line will look indented.
• It’s important to make sure that none of the lines of the string have less whitespace in front of them than in front of the
closing identifier; if this is the case a syntax error will be thrown by PHP.
// This is invalid code
echo <<<EOT
SELECT * FROM `contacts`
WHERE `telephone` IS NOT NULL;
EOT;
stripos() Returns the position of the first occurrence of a string inside another string
(case-insensitive)
stristr() Finds the first occurrence of a string inside another string (case-insensitive)
strlen() Returns the length of a string
strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive)
strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive)
strncasecmp() String comparison of the first n characters (case-insensitive)
strncmp() String comparison of the first n characters (case-sensitive)
strpbrk() Searches a string for any of a set of characters
strpos() Returns the position of the first occurrence of a string inside another string (case-
sensitive)
strrchr() Finds the last occurrence of a string inside another string
strrev() Reverses a string
strripos() Finds the position of the last occurrence of a string inside another string (case-
insensitive)
strrpos() Finds the position of the last occurrence of a string inside another string (case-
sensitive)
• strspn() Returns the number of characters found in a string that contains only
characters from a specified char list
• strstr() Finds the first occurrence of a string inside another string
(case-sensitive)
• strtok() Splits a string into smaller strings
• strtolower() Converts a string to lowercase letters
• strtoupper() Converts a string to uppercase letters
• strtr() Translates certain characters in a string
• substr() Returns a part of a string
• substr_compare()Compares two strings from a specified start position (binary
safe and optionally case-sensitive)
• substr_count() Counts the number of times a substring occurs in a string
• substr_replace() Replaces a part of a string with another string
• trim() Removes whitespace or other characters from both sides of a string