PHP » Strings

The string datatype is typically used to hold textual data. Since websites usually process a lot of text, strings tend to be common in PHP scripts. Fortunately, PHP offers a rich selection of functions with which strings can be analyzed and modified. This section explains many these useful functions.

In PHP, strings are not limited to holding textual data. They can also be used for binary data. This section, however, is devoted to text manipulation and extraction.

There are three different ways to delimit strings. Double quotes should be used when variables or escape sequences inside the string should be interpreted. This means that variable names are replaced with their value, and that escape sequences like \n, \t, and \" can be used to insert special characters. With single quotes, variables and most escape sequences are not interpreted. In the following example, $s1 would contain "Hello world", while $s2 would be "Hello $name".

$name = "world";
$s1 = "Hello $name";
$s2 = 'Hello $name';

The third way of delimiting a string is called "Here doc". The sequence <<< is followed by any identifier. Between this identifier and the next occurrence of it, the string data appears. This can be convenient, for example with long strings containing quotes and line breaks.

$s3 = <<<MYQUOT
Now it does not matter if there are
"quotes" and "things" like that in
the text: ''' """

Strings can be concatenated with the string concatenation operator ".", as in the following example:

$s4= "Hello";
$s5 = $s4 . "world";
// $s5 == "Hello world"

Individual characters in strings can be accessed with curly braces: $s{0} is the first character of $s.

This section presents many useful functions for simple string processing, working on character positions and exact sequences of strings. A much more powerful method of processing strings is called regular expressions. PHP supports both POSIX and Perl style regular expressions, and functions for both of these are also explained in this section. Regular expressions themselves are not covered in this quick reference, as that is a very large subject not directly related to PHP.