str_replace()

str_replace() — Replace all occurrences of the search string with the replacement string.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

Signature

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

Parameters

ParameterTypeWhat it takes
$searcharray|stringThe value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
$replacearray|stringThe replacement value that replaces found search values. An array may be used to designate multiple replacements.
$subjectstring|arrayThe string or array being searched and replaced on, otherwise known as the haystack.
&$countintIf passed, this will be set to the number of replacements performed.

Return value

This function returns a string or an array with the replaced values.

Example

A runnable snippet:

// Provides: <body text='black'> $bodytag = str_replace("%body%", "black", "<body text='%body%'>"); echo $bodytag, PHP_EOL; // Provides: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); echo $onlyconsonants, PHP_EOL; // Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); echo $newphrase, PHP_EOL; // Provides: 2 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count, PHP_EOL;

See also

str_ireplace(), substr_replace(), preg_replace(), strtr()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page str_replace() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.