The Complete PHP str_replace Tutorial

The complete php str replace tutorial

PHP str_replace is a great yet powerful tool for all those wanting to take a string and replace some of its contents. As a native PHP function, you'll benefit from the inherited performance benefit as opposed to writing you're own variant of this function. If you're looking to replace parts of a string in your PHP code then str_replace (short for string replace) is the function for you. We'll explore how it works, the syntax including how to take it further and replace multiple values, and more!

Working with strings in PHP is one of the most common tasks our application will undertake. Printing text to your user or manipulating strings to save into a database are just some examples of this. The easiest way to replace take a string and replace parts of it is by using str_replace. This function takes up to four different parameters with the flexibility to update one or more string occurrences. Let's explore the basic syntax of the function and then learn what each parameter does.

# Basic str_replace syntax

str_replace(
 array|string $search,
 array|string $replace,
 string|array $subject,
 int &$count = null
): string|array

The first parameter of str_replace is the string (or array of strings) that you're looking to replace. This is known as the search term, and this is what PHP will search for in your provided string in order to replace it.

Secondly, the replace parameter is what you'd like PHP to replace the found string(s) with, which can also be an array of strings.

Next is the subject parameter. This is what PHP will search and replace based on the first and second parameters provided.

Finally, the count parameter, which is passed by reference will get populated with the total number of replacements found, which by default will be null.

Once PHP has run your search and replace on a string, it will return either the subject with the replacements applied or an array of string replacements.

It's important to note the order of the provided strings. Therefore, the parameters must be provided from "left to right" in order to get the expected result. Bookmark this page just in case you forget the order next time you're coding and are required to replace strings in PHP. Let's explore some working examples with PHP code that you can copy into your next project. Also, the str_replace function is case-sensitive. If you're looking for a case-nonsensitive string replacement function, try the str_ireplace function which works the same as str_replace, but is case-insensitive.

str_replace in action

Let's focus on replacing (for now) just one string with another, leaving arrays of strings till later. In the following example we're asking PHP to replace any occurrences of "world" (the first parameter) with "earth" (the second parameter) on the string "hello world" (the third parameter).

str_replace("world", "earth", "hello world");

# Outputs
hello earth

The str_replace function in PHP also replaces numbers and other characters aside from just letters, let's explore one of those examples. In the first example, we've asked PHP to replace "5" with "10" and in the second example we're asking PHP to replace the British pound sign "£" with the American dollar sign "$". You'll notice in the second example we didn't ask PHP to replace the number five with the number ten, therefore the output we see is correct which is "the basket cost is $5.99" (not $10.99).

str_replace("5", "10", "the basket cost is £5.99");

# Outputs
the basket cost is £10.99

str_replace("£", "$", "the basket cost is $5.99");

# Outputs
the basket cost is $5.99

Find and replace with nothing

What if we want to replace something with nothing? Maybe we're looking to strip characters off a string, and whilst in PHP there are many ways to approach the same task, for this tutorial we'll show how it's possible using the str_replace function. In the following example, we're now asking PHP to replace the hyphen character "-" with nothing, an empty string (""). Because we're not replacing it with anything PHP will simply strip it away.

str_replace("-", "", "foo bar-");

# Outputs
foo bar

By default, str_replace will search and replace all occurrences it finds, which means it will replace multiple values. Let's take an example where we're looking to replace all occurrences of the same value.

str_replace("blue", "white", "the car is blue and the sky is blue");

# Outputs
the car is white and the sky is white

Using str_replace to replace multiple values

We've explored replacing single strings with other stings, but using str_replace it is also possible to replace multiple values at the same time. We do this by passing the function an array of strings instead of a single array. Let's explore how this works with a PHP code example. Here we're asking PHP to replace all occurrences of "9" and "3" and replace them with "o" and "a", which will output "foo bar". By providing two searches and two replacements they'll get replaced in that order.

str_replace(["9", "3"], ["o", "a"], "f99 b3r");

# Outputs
foo bar

When replacing multiple values with str_replace, it is also possible to have a different number of replacements for the searches. Let's explore how this works. In this example, our search array has two indexes, whereas the replacement array only has one. In this instance, PHP will apply the same replacement to all search elements, so in our example, both commas and full stops get replaced with an empty string, which will strip them out.

str_replace([",", "."], [""], ".f,o.o. b.a,r.");

# Outputs
foo bar

Another common task that we've performed before in our PHP applications is replacing double quotes with single quotes and vice versa. Because we declare strings in PHP with single or double quotes, when we want to use them in variables (like in the example below), we have to ensure we properly escape them using, escape sequence indicators.

str_replace('"', '\'', 'this is a "quote"');

# Outputs
this is a 'quote'

PHP strtr vs str_replace

If you are familiar with the strtr function you might be wondering why you would use str_replace instead. Both functions are string manipulation functions that can be used to replace occurrences of substrings in a given string, however, there are some differences in their functionality and ultimately their usage. Typically you would use strtr to replace specific characters whereas str_replace is used to replace whole substrings. Another way to look at it is if you're looking to replace whole words with something else, use str_replace, otherwise use strtr to replace individual characters.

str_replace count

When using the str_function it is sometimes useful to know the total number of replacements, maybe to show the user or to log. To do this we can use the "$count" variable which gets passed by reference during the function lifecycle. By default this is null, but after each replacement, the count gets incremented. In our example below we are replacing lowercase "p" with uppercase "P" in the word PHP. Which of course will replace 2 letters, setting the count at 2.

str_replace("p", "P", "php", $count);

echo $count;
# Outputs
2

str_replace regex

As the str_replace function is designed to work on fixed strings, it is not possible to use regex here to make replacements. Instead, you are better off using the preg_replace function in PHP, which is designed to work with regex. Performance-wise, if you're not using regex to make the replacement, you are better off using str_replace or str_ireplace functions.

Conclusion

The str_replace function is a fast and easy way to make changes to strings in your PHP applications. Great for swapping out words with other words, replacing multiple values by passing arrays instead of fixed strings. Remember the parameter order is important, and take care if you're looking for case-sensitive string replacements.

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all