PHP String Replace

The PHP string replace function replaces all occurrences of a specified string (in a "host string") with another replacement string. The string replace function in PHP is known as str_replace.

This function may be useful, for example, in a situation where we have a string containing a name multiple times, and we want to replace that name with another name. This function makes it very easy to perform a search and replace. The PHP tutorial below demonstrates.

PHP str_replace Syntax

The syntax for the str_replace function is shown below:

str_replace($find, $replace, $actual_string);

Where $find is the string (or an array of strings) we are searching for, $replace is the string which contains what we want to replace $find with when found, and $actual_string is the actual string which we will be performing the function on.

PHP String Replace Example

Let us say we had a sentence and we wanted to replace a particular string with another. We could use the following code to perform the replace:

$s = 'I love another tutorial site so much.';
$s = str_replace('another tutorial site', 'Tutorial Arena', $s);
echo $s;

The result:

I love Tutorial Arena so much.

As we can see, we have successfully replaced the string "another tutorial site" with "Tutorial Arena". Using the str_replace function, we are able to quickly and easily replace multiple occurrences of a string within another string.

PHP String Replace Array

Now let us say that we do not have only one term that we want to replace. Suppose we have more than one terms that we want to replace with a particular term. PHP makes this very easy. We simply need to put all the terms we want to replace in an array and then use the function just as usual.

Look at the following code:

$s = 'Stacey loves to learn HTML and Jessica loves to learn Java.';
$find = array('HTML', 'Java');
$s = str_replace($find, 'PHP', $s);
echo $s;

Would result in:

Stacey loves to learn PHP and Jessica loves to learn PHP.

Exactly what we wanted. What we have done is create an array (of the words we want to replace) containing the words 'HTML' and 'Java'. We then call the string replace function, passing this array of words to it, and it will look for each one and replace it with the word we specify. In this case the word we specified was 'PHP'.

Therefore, two word replacements were made and the result is as what we saw.


We hope this PHP string replace tutorial has helpful. We saw how to replace a single word with another, and we also saw how to replace an array of words with a word.

Suppose that instead of replacing a string with another, you wanted to simply find out if the target string was present in the host string; you would use the PHP string contains function for that.

Another useful PHP string manipulation function that you might be interested in is the PHP Substr Function.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...