PHP String Handling Functions

Share this article

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

Frequently Asked Questions about PHP String Handling Functions

What are some common PHP string handling functions and their uses?

PHP provides a wide range of string handling functions. Some of the most commonly used ones include:

    1. strlen(): This function returns the length of a string.

    1. str_replace(): This function replaces some characters with some other characters in a string.

    1. strpos(): This function finds the position of the first occurrence of a string inside another string.

    1. strtolower(): This function converts a string to lowercase.

    1. strtoupper(): This function converts a string to uppercase.

    1. substr(): This function returns a part of a string.


These functions are used to manipulate and handle strings in various ways, such as changing the case of a string, finding the length of a string, replacing parts of a string, and more.

How can I convert a string to an array in PHP?

In PHP, the str_split() function is used to convert a string into an array. This function splits a string into an array by length. Here’s an example:

$string = "Hello, World!";
$array = str_split($string);
print_r($array);

In this example, the str_split() function splits the string “Hello, World!” into an array where each element is a single character from the string.

How can I compare two strings in PHP?

PHP provides several functions to compare strings, including strcmp(), strcasecmp(), strnatcmp(), and strnatcasecmp(). The strcmp() function compares two strings binary safe and case-sensitive. Here’s an example:

$string1 = "Hello";
$string2 = "World";
$result = strcmp($string1, $string2);
if ($result < 0) {
echo "$string1 is less than $string2";
} else if ($result > 0) {
echo "$string1 is greater than $string2";
} else {
echo "$string1 is equal to $string2";
}

In this example, the strcmp() function compares the strings “Hello” and “World”. The function returns < 0 if string1 is less than string2; > 0 if string1 is greater than string2, and 0 if they are equal.

How can I reverse a string in PHP?

The strrev() function in PHP is used to reverse a string. Here’s an example:

$string = "Hello, World!";
$reversed = strrev($string);
echo $reversed; // Outputs: "!dlroW ,olleH"

In this example, the strrev() function reverses the string “Hello, World!”.

How can I remove white spaces from a string in PHP?

The trim() function in PHP is used to remove white spaces and other predefined characters from both sides of a string. Here’s an example:

$string = " Hello, World! ";
$trimmed = trim($string);
echo $trimmed; // Outputs: "Hello, World!"

In this example, the trim() function removes the white spaces from the beginning and end of the string ” Hello, World! “.

James AppleyardJames Appleyard
View Author

James Appleyard is from the UK. He built his first website back in 2000 and has been hooked ever since. For his day job he helps to maintain a large website for a major international IT company. In his free time, James has completed an MSc in Web Applications Development and enjoys exploring the depths of PHP and WordPress. More recently, James has been volunteering for IT4Communities in the UK building websites for charities, good causes, and not-for-profit organizations. When he has any time left over he enjoys cooking, reading, and sleeping.

Beginner
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week