Summary: in this tutorial, you will learn about PHP string and various built-in string functions to manipulate strings.
Table of Contents
Defining a PHP string
In PHP, a string is a sequence of characters. There are four ways to define a literal string in PHP: single quoted, double quoted, heredoc syntax and nowdoc syntax.
Single-quoted string vs. double-quoted string
To define a string, you assign a literal string value that is enclosed in single quotation marks (‘) to a new variable as follows:
1 2 3 | <?php $str = 'This is a string'; |
This is the simplest way to define a string in PHP. You can also use double quotation marks (“) as the following example:
1 2 | <?php $str2 = "PHP string can be surrounded by double quotation marks"; |
When you use double quotation marks to enclose a string, PHP give you additional features:
- A double-quoted string accepts variables in a string. PHP will parse and replace the variable names by their values. This is similar to variable interpolation feature in Perl.
- A double-quoted string accepts special characters e.g., \n, \r, \t…by escaping them.
Let’s take a look at the following example:
1 2 3 4 5 | <?php $site_name = 'zentut.com'; $message = "Welcome to $site_name!"; echo $message; // Welcome to zentut.com! |
PHP replaces the $site_name
variable in the $message
string by its value 'zentut.com'
.
The following example demonstrates how to use special characters inside a double-quoted string:
1 2 3 4 5 6 | <?php $foo = 'boy'; $message = "Hello\t$foo"; echo '<pre>' . $message . '</pre>'; //Hello boy |
PHP replaces the special character \t
by the actual horizontal tab character inside the $message
string.
It is a best practice to use single-quoted string because PHP does not have to parse and evaluate the single-quoted string as it does for double-quoted string.
heredoc and nowdoc strings
In case you want to define a string that contains a lot of single and double quotation marks, you can use heredoc and nowdoc syntax to avoid using escape characters.
The following illustrates the heredoc syntax:
1 2 3 | $str = <<<IDENTIFIER put string here IDENTIFIER; |
First, you specify the operator <<<
, followed by an IDENTIFIER
, and then a newline. Next, you put a string value. Finally, you use the same IDENTIFIER
to close the string.
The following example defines a string using heredoc syntax:
1 2 3 4 5 6 7 8 9 10 | <?php $s = <<<EOT I'm a string that is using heredoc syntax. I can contain single quotation marks (') and double quotation mark(") without using escape character EOT; echo $s; |
Notice that PHP replaces the variables by their values in a string defined using heredoc syntax.
The nowdoc syntax is similar to the heredoc syntax except the identifier in nowdoc syntax is enclosed in single quotation marks.
1 2 3 4 5 6 7 8 | $s = <<<'EOT' I'm a string that is using nowdoc syntax. I can contain single quotation marks (') and double quotation mark(") without using escape character EOT; echo $s; |
In addition, PHP does not parse and replace variables by their values in a string defined using nowdoc syntax.
Accessing characters in a string
To access a character of a string at a particular position, you use the following syntax:
1 | $s[index] |
You put an index between square brackets []
after the string variable. The first position of a string is zero(0). You can read and change the content of a string using index as the following example:
1 2 3 4 5 6 | <?php $str = 'this is a PHP string'; $str[0] = 'T'; echo $str; |
Getting the length of a string
To get the number of characters in a string, you use a built-in function strlen()
. It accepts a string as a parameter and returns the number of characters in that string. Let’s take a look a the following example of using the strlen()
function:
1 2 3 4 | <?php $str = 'this is a PHP string'; echo strlen($str); |
If you want to count the number of words in a string, you use the str_word_count()
function instead.
1 2 3 4 | <?php $str = 'this is a PHP string'; echo str_word_count($str); // 5 |
Comparing strings
PHP provides two built-in functions strcmp()
and strcasecmp()
that allow you to compare two strings. Both functions accept two string arguments and return an integer number:
- If two strings are equal, it returns
0
. - If the first string is greater than the second string it returns a number that is greater than
0
. - If the first string is less than the second string, it returns a number that is less than
0
.
The only difference between strcmp()
and strcasecmp()
functions is that the strcasecmp()
function compares strings in case-insensitive manner whereas the strcmp()
function does not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php $str1 = 'PHP String'; $str2 = 'php string'; $result = strcasecmp($str1,$str2); if($result == 0){ echo '$str1 and $str2 are equal'; }else if($result > 0){ echo '$str1 is greater than $str2'; }else{ echo '$str1 is less than $str2'; } |
If you replace the strcasecmp()
function by strcmp()
function in the code snippet above, the output will be different.
Concatenating strings
PHP allows you to concatenate strings using period ( .
) operator. If you concatenate a string with a variable that is not a string type, the result is a string because PHP automatically converts the non-string variable into a string variable before concatenating.
The following example demonstrates strings concatenation:
1 2 3 4 5 6 7 8 9 | <?php $str = 'This is' . ' a string'; echo $str . '<br/>'; $age = 22; $s1 = 'years old'; $s2 = 'Are you ' . $age . ' ' . $s1 . '?'; echo $s2; |
Searching strings
PHP provides you several useful function for searching strings including strstr()
, strpos()
, strrpos()
, substr_count()
and strpbrk()
.
Checking if a string contains a substring
To check if a string contains a particular substring, you use the strstr()
function. The strstr()
accepts two parameters: a string that to be checked and a substring that you want to search for. If the substring found, the function returns the portion of the string that begins of the found text to the end of the string. It returns false if the substring cannot be found.
1 2 3 4 | <?php $str = 'Find a substring in a string'; $sub_str = 'substring'; echo strstr($str,$sub_str); //substring in a string |
Locating position of a substring within a PHP string
If you want to know exact position of a substring within a string, you use the strpos()
function. It returns the first occurrence of a substring in a string.
1 2 3 4 | <?php $str = 'Using strpos function in PHP'; $sub_str = 'strpos'; echo strpos($str,$sub_str); // 6 |
The strrpos()
function is similar to the strpos()
function except it returns the position of the last occurrence of a substring in a string.
1 2 3 4 5 | <?php $str = 'String function'; $sub_str = 'n'; echo strpos($str,$sub_str); // 4 echo strrpos($str,$sub_str); // 14 |
Getting the number of occurrences of a substring
To get how many times a substring that appears in a string, you use the substr_count()
function. The substr_count()
function is useful in many cases e.g., you can count how many times a keyword is mentioned in an article to calculate its density.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $str = <<<EOT This is sample text that demonstrates how to calulate keyword density in an article. We can use this function for on-page optimization function in SEO software. EOT; $keyword = 'function'; $word_count = str_word_count($str); $keyword_count = substr_count($str,$keyword); if($word_count > 0){ $density = $keyword_count * 100 / $word_count; echo number_format($density, 2, '.', '') . '%'; //7.69% } |
Checking if a string contains any character in a set of characters
To check if a string contains any character in a set of characters, you use strpbrk()
function. The strpbrk()
function accepts two parameters: a string and a set of characters that you want to find. It returns a substring starting from the character found or false
if character in a set of characters does not appear in the string. The strbbrk()
function is useful in many cases e.g., you can check if a user name contains any special character in a set !, @, $, %… as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $username1 = 'zentut'; $username2 = 'zen@tut'; $not_allowed_chars = '!@#$%^&*'; if(strpbrk($username1, $not_allowed_chars)){ echo 'invalid username because it contains one of ' . $not_allowed_chars; } if(strpbrk($username2, $not_allowed_chars)){ echo 'invalid username because it contains one of ' . $not_allowed_chars; } |
Replacing in strings
PHP provides some useful string functions to replace some portions of a string with different strings including str_replace()
, substr_replace()
and strst()
.
Replacing all occurrences of a search string
To replace all occurrences of a search string with the replacement string, you use the str_replace()
function. Let’s take a look at the following example:
1 2 3 4 5 6 7 8 9 | <?php $str = 'This is an example of a string that demonstrates string replacement'; echo str_replace('string', 'text', $str); // This is an example of a text // that demonstrates text replacement |
We replaced all occurrences of ‘ string
‘ by ‘ text
‘ in the string $str
.
To count how many times the search string was replaced, you need to pass the fourth argument to the function as follows:
1 2 3 4 5 6 7 8 9 | <?php $str = 'This is an example of a string that demonstrates string replacement'; $times = 0; str_replace('string', 'text', $str,$times); echo "The string was replaced $times time(s)"; |
Removing whitespace
To remove whitespace from:
- the beginning of a string you use the
ltrim()
function. - the end of the string you use the
rtrim()
function - both the beginning and the end of a string you use the
trim()
function.
Let’s take a look at the following example:
1 2 3 4 5 6 7 8 9 | <?php $s1 = ' a string with whitespace at the beginning'; $s2 = 'a string with whitespace at the end '; $s3 = ' a string with whitespaces at the beginning and the end '; echo ltrim($s1) . '<br/>'; echo rtrim($s2) . '<br/>'; echo trim($s3) . '<br/>'; |
With those functions, you can remove other characters other than whitespace if you specify them as the second argument.
For more information on string function, check it out the PHP string functions.
In this tutorial, you have learned about the PHP string and a lot of useful string functions that allow you to manipulate strings in PHP.