Handling Strings in PHP

PHP provides a large number of string functions. If you are just learning PHP, reading through the list in the PHP manual can be a bit daunting. This tutorial organizes the most commonly used functions into categories and demonstrates their use in common string handling tasks.

See examples that describe and demonstrate how to:

  • Obtain the length of a string or the number of words it contains: strlen, str_word_count, and substr_count.
  • Change the case of all or some of the characters in a string: strtolower, strtoupper, ucfirst, lcfirst, and ucwords.
  • Search for one string within another: strpos, strrpos, strstr, and strrchr.
  • Replace substrings in strings: str_replace, substr_replace, and strtr.
  • Compare two strings: strcmp, strnatcmp, strncmp, plus comparison operators.
  • Convert strings to arrays: explode and str_split.
  • Clean up strings, removing whitespace or other unwanted characters: trim, rtrim, ltrim, and strip_tags.
  • Display and format strings: echo, print, word_wrap, nl2br, number_format, and var_dump.

But first, we cover some basic information about strings in PHP. See also how you can check to be sure a variable is a string and what to do if it's not.

Strings in Single Quotes, Double Quotes, and Heredoc

You can use single quotes or double quotes to specify a string in PHP. However, variables and special characters (escape sequences)[1] are handled differently depending on whether they are enclosed in double quotes or single quotes. Consider the following example:

$name = 'Jon';
// string in single quotes
$str = 'Hi, my name is $name.\nWhat\'s yours?';

// output $str contents using var_dump
var_dump($str); // string(36) "Hi, my name is $name.\nWhat's yours?"

// string in double quotes
$str2 = "Hi, my name is $name.\nWhat's yours?";
var_dump($str2);
// View Source display:
/*
string(33) "Hi, my name is Jon.
What's yours?"
*/

Notice that in the double-quoted string, the value of the variable $name is inserted, and that a new line replaces \n.[2] Compare this with the single-quoted string, where the output almost exactly matches the input, except an apostrophe replaces \'.

Double-quoted strings are used more often in PHP because of their ability to expand variables and escape sequences, including \n (newline), \r (carriage return), \t (tab), \\ (backslash), \$ (dollar sign), and \" (double quote).[3] In single quotes, only the apostrophe (or single quote) and backslash are recognized as escape sequences.[4]

Heredoc Syntax

Heredoc syntax expands variables as well as the same escape sequences as double quotes. But without the double quotes, there is no need to escape double quotes within the string itself. This is very helpful for declaring strings that include HTML markup.

A string declared using heredoc syntax begins with the <<< symbol, an identifier, and a new line. It ends with that same identifier at the far left of a new line followed by a semicolon:

// example variables to output in heredoc
$name = 'John Smith';
$date = 'June 14, 2016';
$total = 326.59;

// string in heredoc syntax
$str = <<<EOS
<h3 class="greet">Hello $name,</h3>
<p class="tot">Your $date order total is: \$$total</p>
EOS;

var_dump($str);
// View Source display:
/*
string(102) "<h3 class="greet">Hello John Smith,</h3>
<p class="tot">Your June 14, 2016 order total is: $326.59</p>"
*/

Notice that the values of the variables are substituted into the output, and that the value of the $total variable, which is a floating point number, has been seamlessly included in the string.[5] Notice also that the \$ escape sequence has been replaced with the literal dollar sign in front of the $total value.

See the PHP Manual for more details on heredoc syntax.

String Operators

PHP includes two string operators that provide the means of appending strings to one another: the concatenation operator (.), and the concatenating assignment operator (.=).

// example variables
$first = 'John';
$last = 'Smith';

// concatenation operator combining strings
$name = $first . ' ' . $last;

$greet = 'Hello ';
// using concatenating assignment operator
$greet .= $name;
echo $greet; // Hello John Smith

The concatenating assignment operator appends the right-hand operand to the value of the left-hand operand, and then assigns the result to the left-hand operand.

Using Curly Braces in Strings

Curly braces can be used in strings to enable you to include expressions which would otherwise trigger errors. Consider the following example:

$fruit = 'banana';
echo "I have included 2 $fruits in your lunch box today.";
// Notice:  Undefined variable: fruits

// enclose variable name in curly braces
echo "I have included 2 {$fruit}s in your lunch box today.";
// I have included 2 bananas in your lunch box today.

The PHP Manual provides more information and examples on the use of curly braces for outputting complex expressions in strings.


  1. An escape sequence combines a backslash (\) with another character to represent a special character. For example, \n represents a newline, and \t represents a tab. Escape sequences are also used to indicate that the character following the backslash should be interpreted literally when otherwise it would have special meaning within the string (such as the dollar sign and double quote in a double-quoted string). ^
  2. You will be able to see that the new line has been inserted if you view source. New lines are not displayed in the browser window. Find out more in our presentation on Displaying and Formatting Strings in PHP. ^
  3. See the complete list of escape sequences in the PHP Manual. ^
  4. The \' escape sequence is supported in single-quoted strings, and the \" escape sequence is supported in double-quoted strings. This allows these characters (' and ") to be included in strings without being interpreted as the end of the string. ^
  5. Find out more about the automatic type conversion that can take place in PHP. ^