PHP String Handling Functions

    James Appleyard
    Share

    PHP has a vast selection of built-in string handling functions that allow you to easily manipulate strings in almost any possible way. However, learning all these functions, remembering what they do, and when they might come in handy can be a bit daunting, especially for new developers. There is no way I can cover every string function in one article, and besides, that is what the PHP manual is for! But what I will do is show how to work with some of the most commonly used string handling functions that you should know. After this, you’ll be working with strings as well as any concert violinist!

    On the Case

    PHP offers several functions that enable you to manipulate the case of characters within a string without having to edit the string character by character. Why would you care about this? Well maybe you want to ensure that certain text is all in upper case such as acronyms, titles, for emphasis or just to ensure names are capitalized correctly. Or maybe you just want to compare two strings and you want to ensure the letters you are comparing are the same character set. The case manipulation functions are pretty easy to get to grips with; you just pass the string as a parameter to the function and the return value you is the processed string.

    If you wanted to ensure all the letters in a specific string were uppercase, you can use the strtoupper() function as follows:

    <?php
    $str = "Like a puppet on a string.";
    $cased = strtoupper($str);
    // Displays: LIKE A PUPPET ON A STRING.
    echo $cased;

    It is perhaps obvious but still worth noting that numbers and other non-alphabet characters will not be converted.

    As you can probably guess, the strtolower() function does the exact opposite of strtoupper() and converts a string into all lowercase letters:

    <?php
    $str = "LIKE A PUPPET ON A STRING.";
    $cased = strtolower($str);
    // Displays: like a puppet on a string.
    echo $cased;

    There may be other times when you want to ensure certain words, such as names or titles, just have the first letter of each word capitalized. For this you can use the ucwords() function:

    <?php
    $str = "a knot";
    $cased = ucwords($str);
    // Displays: A Knot
    echo $cased;

    It is also possible to manipulate the case of just the first letter of a string using the lcfirst() and ucfirst() functions. If you want the first letter to be lowercase, use lcfirst(). If you want the first letter to be uppercase, use ucfirst(). The ucfirst() function is probably the most useful since you can use it to ensure a sentence always starts with a capital letter.

    <?php
    $str = "how long is a piece of string?";
    $cased = ucfirst($str);
    //Displays: How long is a piece of string?
    echo $cased;

    A Quick Trim

    Sometimes a string needs trimming round the edges. It may have whitespace or other characters at the beginning or end which needs removing. The whitespace can be an actual space character, but it can also be a tab, carriage return, etc. One example of when you might need to do something like this is when you’re working with user input and you want to clean it up it before you start processing it. The trim() function in PHP lets you to do just that; you can pass the string as a parameter and all whitespace from the beginning and end of that string will be removed:

    <?php
    $str = "  A piece of string?  ";
    // Displays: string(22) " A piece of string? "
    var_dump($str);
    
    $trimmed = trim($str);
    // Displays: string(18) "A piece of string?"
    var_dump($trimmed);

    trim() is also multi-purpose in that in addition to the string you can also pass it a set of characters and it will remove any that match from the beginning or end:

    <?php
    $str = "A piece of string?";
    $trimmed = trim($str, "A?");
    // Displays: string(16) " piece of string"
    var_dump($trimmed);

    You do need to be careful when you work with these additional characters since trim() will only remove whitespace if you specifically provide it as one of the characters you want removed:

    <?php
    $str = "A piece of string?";
    $trimmed = trim($str, "A ?");
    // Displays: string(15) "piece of string"
    var_dump($trimmed);

    Even though trim() only removes characters at the start and end of a string, it has removed both “A” and the space because when “A” is removed the space becomes the new start of the string, and so that is also removed.

    There are also ltrim() and rtrim() functions in PHP which are similar to the trim() function but only remove whitespace (or other specified characters) from the left or right of the string respectively.

    How Long is a (Piece of) String?

    Very often when working with strings, you’ll want to know how long it is. For example, when dealing with a form, you may have a field where you want to make sure users can’t go over a certain number of characters. To count the number of characters in a string, you can use the strlen() function:

    <?php
    $str = "How long is a piece of string?";
    $size = strlen($str);
    // Displays: 30
    echo $size;

    Cutting Strings Down to Size

    Another common situation is finding specific text within a given string and “cutting it” out so you can do something else with it. To cut a string down to size, you need a good pair of scissors, and in PHP your scissors are the substr() function.

    To use the substr() function, pass the string you want to work with as a parameter along with a positive or negative integer. The number determines where you’ll start cutting the string; 0 starts you off at the first character of the string (remember that when you count through a string, the first character on the left starts at position 0, not 1).

    <?php
    $str = "How to cut a string down to size";
    $snip = substr($str, 13);
    //Displays: string down to size
    echo $snip;

    When you use a negative number, substr() will start backwards from the end of the string.

    <?php
    $str = "How to cut a string down to size";
    $snip = substr($str, -7);
    //Displays: to size
    echo $snip;

    An optional third parameter to substr() is the length, another integer value that allows you to specify the number of characters you want to extract from the string.

    <?php
    $str = "How to cut a string down to size";
    $snip = substr($str, 13, 6);
    //Displays: string
    echo $snip;

    If you just need to find the position of a particular piece of text within a string and nothing else, you can use the strpos() function which returns the position your selection is from the start of the string. A useful trick, especially when you don’t know the starting position of the text you to cut from a string, is to combine the two functions. Rather than specifying a start position as an integer, you can search for a specific piece of text and then extract that.

    <?php
    $str = "How to cut a string down to size";
    $snip = substr($str, strpos($str, "string"), 6);
    //Displays: string
    echo $snip;

    Swap Shop

    Finally, let’s look at replacing a piece of the string with something else, for which you can use str_replace() function. This is ideal for situations where you just want to swap out instances of specific words or a set of characters in a string and replace them with something else:

    <?php
    $oldstr = "The cat was black";
    $newstr = str_replace("black", "white", $oldstr);
    // Displays: The cat was white
    echo $newstr;

    You can also provide arrays to str_replace() if you want to replace multiple values:

    <?php
    $oldstr  = "The flag was red white and blue.";
    $america = array("red", "white", "blue");
    $germany = array("black", "red", "yellow");
    $newstr = str_replace($america, $germany, $oldstr);
    // Displays: The flag was black red and yellow.
    echo $newstr;

    str_replace() is case-sensitive, so if you don’t want to worry about that then you can use its case-insensitive sibling instead, str_ireplace().

    Summary

    Hopefully, this article has given you a taste of some of the things you can do with strings in PHP and made you hungry to learn more. I’ve really barely scraped the tip of the iceberg! The best place to find out more about all of the different string functions is to take some time to read the String Functions page in the PHP Manual.

    I’d love to know which string functions you find yourself using most often, so feel free to mention them in the comments below.

    Image via Vasilius / Shutterstock