PHP String Handling Functions

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Geert

    Note that PHP5 does not natively support Unicode.
    <?php
    strlen('abc'); // 3
    strlen('àbc'); // 4

  • http://keryx.se/ Lars Gunther

    One thing needs to be mentioned and that is that almost all these functions are ISO-8859-1 specific. If you’re using UTF-8 (and you should), you must use the equivalent mb_ function.

    • Steffen

      The mb_* are overhyped IMO. There are not that many cases where you have to use them, even if your strings are UTF-8. For example, if your strpos’s needle is an ASCII character, you can stick with the faster strpos instead of mb_strpos even if your haystack is UTF-8.

      • Tomica

        Perhaps not if English is the only language you’ll ever speak. For the rest of us (that is 90% of human kind) mb_ is a total must:
        1′ if you’re working with non-ascii Latin scripts;
        2′ if you’re working with non-latin scripts (Cyrillic, Greek, Hebrew, Arabic etc.);
        3′ if you’re working with pictograms (CJK);
        4′ any other case where for any reason you need to make use of AT LEAST one of 109,885 Unicode non-ascii characters.
        If anyone should ask me how often is that I use the mb_ functions, I would happily admit that without them PHP would be totally unusable for me.

  • http://www.google.com rajesh

    excellent

  • Bigorangemachine

    I like to use something like
    myisstr()

    Its helpful when validating forms. You ensure the data type is correct and the input isn’t a bunch of white space.
    function myisstr($str){
    if(is_string() && strlen(trim($str))>0){return true;}
    return false;
    }

    I also built a function that cuts a string off at the left side and right side (like Rtrim and Ltrim) but only does it if the comparision string is at the front/end.

  • http://www.talentvisionz.com Aryashree Pritikrishna

    Nice article! Thanks again

  • ConfinedSpace

    For performance reasons, should single quotes (‘) be used instead of double quotes (“) with strings (without variables in)?

    $str = ‘How long is a piece of string?’;

    • James

      There has been quite a lot of debate about that and there are tons of posts and bench mark tests trying to prove it one way or another. I think that the conclusion is that the difference in modern PHP is negligible. See http://nikic.github.com/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html. So it is more about personal preference, code readability and maintainability than anything else. I personally find using double quotes more readable, especially in examples like this.

  • Shadow Caster

    How about an article about how to work with numbers in PHP – how do I do operations with numbers like add, divide, subtract and multiply? I’m having so much difficulty with these really complex concepts. Please be extremely descriptive so I can understand it…

    Seriously though. This article is completely unsuitable for a website called PHPMaster. If people want to learn the very basics they should RTFM.

    • Wizard-of-the-Moor

      hear hear !
      It is a bit arrogant to take up our scarce time to read something that would be taught in primary programming prparatory school and really is a fundamental foundation of programming.

    • http://zaemis.blogspot.com Timothy Boronczyk

      Please keep in mind that PHPMaster is not a site exclusively for “masters,” but also for those at various stages in their journey to masterhood. To help readers better find articles at their skill level, we have the following levels:

      Beginner – for articles intended for the absolute beginner. These teach rudimentary concepts, such as what variables are, arrays, functions, etc. Some examples are:
      * Error Handling in PHP – Sneha Heda
      * Form Validation with PHP – Iain Tench
      * Introduction to Arrays – J Armando Jeronymo

      Intermediate – for articles that someone who has been programming for a bit can easily follow along and learn from. These often deal with real-world problems or teach concepts that will help them write better code, such as using a framework, implementing a design pattern, basic security principles, etc. Examples are:
      * Rapid Application Development with CakePHP – Vito Tardia
      * Autoloading in PHP and the PSR-0 Standard – Hari TK
      * Targeted Geolocation with Geonames – Lukas White

      Advanced – for articles indented for more experienced programmers. Such articles would include exploring the inner-workings of a framework or library, new/advanced language features, etc. Examples:
      * Understanding OAuth – Tweeting from Scratch – Dustin Runnells
      * Under the Hood of Yii’s Component Architecture – Steven O’Brien
      * ClamAV as a Validation Filter in Zend Framework – Matthew Setter

      Expert – for articles that target the “serious” programmer. They deal with theoretical ideas, explain in-depth why a particular design pattern works, PHP internals, etc. Examples are:
      * Building a Domain Model – An Introduction to Persistence Agnosticism – Alejandro Gervasio
      * The Liskov Substitution Principle – Alejandro Gervasio
      * Compile PHP on Windows – Timothy Boronczyk

      The levels are arbitrary, fluid, and not super-granular, but we’ve tried to create a scheme that broadly mirrors the different experience levels found throughout the community.

      There are currently efforts under way to make articles available by theme (e.g. Geolocation, E-Commerce, Design Patterns, etc.) which will help people to more easily find the articles that will benefit them the most, but I don’t have a time frame for that yet.