Strings are one of the fundamental scalar types in many programming languages, including PHP. They represent text data, from individual characters to entire documents.

The simplest string programming involves single-byte text, which can represent 256 different characters. ASCII is the most common encoding. The core PHP language has many useful functions to manipulate such strings.

How to Show the Contents of a String

If you’ve done any programming in PHP, you’ve probably come across echo, but you may not realize that it’s actually not a function at all. In fact, echo is a language construct, so even if you use it more than any real string function, you can’t always use it in place of a function.

You’ll almost always use it like this:

        echo "Hello, world";
    

But you can actually call it like a function:

        echo("Hello, world");
    

Although it looks like it, this still isn’t actually a function call. For example, you cannot assign its return value to a variable:

        $a = echo("Hello, world");
Parse error: syntax error, unexpected 'echo' (T_ECHO)

Another way of outputting a string’s value is using print. Again, this isn’t really a true function, although it’s closer to one than echo. Like echo, you can call it without parentheses:

        print "Hello, world";
    

But, unlike echo, it does return a value which you can assign, although that value is always 1:

        $a = print("Hello, world");
echo $a; // 1

1. Outputting a String Using a Real Function

The printf function is actually a real function. Like echo and print, it outputs strings, but it has some unique behaviour which mirrors the same function from the c language:

        $username = "John";
$length = printf("Hello, %s", $username); // "Hello, John"
echo $length; // 11

The first argument is still a string, enclosed in double quotes. But printf will carry out various replacements on special character sequences inside the string. These sequences begin with a percent symbol, like the one above, %s. In this specific case, %s stands for a string, and printf replaces it with the next argument, which is the value of $username.

The printf function returns a useful value, the length of the formatted string. This can be useful for code that cannot know the length in advance, when passing variables to printf, for example. You might use that return value to determine how much physical space the string will occupy on a command line.

2. Getting the Length of a String

Talking of string length, the standard way of determining the length of a string is the strlen function. This function is very straightforward: it takes a single string argument and returns the number of bytes as an integer. As mentioned earlier, for ASCII text, the number of bytes is the same as the number of characters:

        $length = strlen("Hello, World");
echo $length; // 12

3. Extracting Part of a String

A very common task, when dealing with strings, is the extraction of part of that string. There are several ways of doing this, and the first presented here specifies the position and length of the required substring. The substr function extracts a fixed part of a string according to these parameters.

        $greeting = substr("Hello, World", 0, 5);
echo $greeting; // "Hello"

Note that, as in most programming languages, PHP counts string offsets from 0. PHP differs from some languages in that this function’s second parameter is the length of the resulting string.

Related: The Worst and Hardest Programming Languages

Another difference is that PHP supports negative values for both offset and length. If offset is negative, the result will start counting from the end of the string, not the start:

        $greeting = substr("Hello, World", -5, 5);
echo $greeting; // "World"

If length is negative, it will refer to the number of characters removed, rather than the number included:

        $greeting = substr("Hello, World", 0, -6);
echo $greeting; // "Hello,"

4. Searching Within a String

An important part of text processing involves finding the location of one string within another. In PHP, you can achieve this with the strpos function:

        $pos = strpos("Hello, World", ",");
echo $pos; // 5

You can use strpos in conjunction with substr to provide a more general-purpose method for extracting part of a string:

        $string = "Hello, World";
$pos = strpos($string, ",");
$first_part = substr($string, 0, $pos);
echo $first_part; // "Hello"

5. Converting the Case of a String

Traditional ASCII strings have well-defined uppercase and lowercase variants. The uppercase version of a is A. The lowercase of Z is z. The strtoupper and strtolower functions perform these conversions. They do so for each character in an ASCII string:

        $original = "hello, WORLD";
$upper = strtoupper($original);
$lower = strtolower($original);
echo "$lower $upper"; // "hello, world HELLO, WORLD"

6. Eliminating Whitespace

Sometimes, you’ll end up with a string that has leading or trailing whitespace: spaces, tabs, or newline characters. This is often unwanted, but trim can remove it:

        $trimmed = trim(" Hello, World ");
echo $trimmed; // "Hello, World"

7. Breaking Up a String by a Separator

The explode function sounds dangerous but don’t worry, it doesn’t cause any lasting damage! Instead, it converts a string into an array of strings, separated by another string — often a character. It can be useful if you want to break a sentence up into separate words, for example.

        $sentence = "The quick brown fox jumps over the lazy dog";
$words = explode(" ", $sentence);

The $words variable is now an array containing individual words:

        [ "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" ]
    

8. Breaking Up a String Into Fixed Length Substrings

Like explode, the str_split function breaks up a string into an array of smaller strings. Unlike explode, the final strings are not determined by their contents, but by their length.

        $parts = str_split("Hello, World", 6);
    

The $parts array now contains two substrings, each one six characters in length:

        [ "Hello,", " World" ]
    

9. Search and Replace Within a String

You can perform a simple search and replace operation on a string using str_replace. It takes three arguments: a string to search for, a replacement string, and an original string to search. The function returns the new string:

        $result = str_replace("o", "OO", "Hello, World");
echo $result; // "HellOO, WOOrld"

PHP Provides Many Useful Ways of Working With Text

Since PHP is often used in web development, dealing with text is a common task.

The functions presented here are amongst the most useful for processing text using PHP. There are around one hundred string-handling functions built into the language itself.

Do remember that the functions shown here are for use with ASCII strings, not Unicode ones. PHP also has support for Unicode, and other multibyte character encoding schemes, with a separate set of functions.