PHP Str_replace

By using the str_replace function, we can find every occurrence of a particular string or array and replace it with another string or array.

str_replace Syntax

The correct syntax to use with the str_replace function is:

str_replace(searchfor, replacewith, searchin);

Search For:

This is the string or array you wish to search for.

Replace With:

This is the string or array you wish to replace all the occurrences of what you searched for with.

Search In:

This is what you wish to search. Once str_replace has finished its function, your “searchin” string will have been modified with all the “searchfor” values substituted with the “replace with” values.

Str_replace Example

$originalstring = “My favorite color is favcolor.”;

$black = str_replace(“favcolor”, “black”, $originalstring);

$white = str_replace(“favcolor”, “white”, $originalstring);

echo “If black: “. $black . “<br />”;
echo “If white: “. $white;

This bit of code would display:

If black: My favorite color is black.
If white: My favorite color is white.

Notice that we replaced every occurrence of “favcolor” in our original string with either $black or $white.

First, we searched for every occurrence of “favcolor” and replaced it with “black”, then named this $black.

Then, we searched for every occurrence of “favcolor” and replaced it with “white”, then named this $white.

We then echoed the modified string based on each str_replace function performed.

Notice how we joined each value together using the concentration operator (.).

For more information on using concentration operators, see PHP Operators.