PHP » Strings » str_replace()

string str_replace(string search, string replace, string s [, int count])
Sequence of characters to be replaced.
New sequence of characters to insert.
String to search and replace in.

Replaces all occurrences in a string.

str_replace() returns a new string with all the occurrences of the search string replaced with the replacement string. The optional count, available in PHP 5 and above, contains the number of replacements made when the function returns. The search and replace parameters can also be arrays of strings, in which case the occurrences of the search strings at each index will be replaced with the replacement string at the same index.



$s = "Three pizza slices or a whole pizza?";
print str_replace("pizza", "cake", $s) . "<br>";
print str_replace(array("pizza", "Three"), array("cake", "Four"), $s);

Three cake slices or a whole cake?
Four cake slices or a whole cake?

First str_replace() is used to replace all occurrences of "pizza" with "cake". It then is used to also change "Three" to "Four", by using arrays for the searches and replacements.

See Also: