What does str_replace() do?
str_replace() finds every occurrence of $search in $subject and replaces it with $replace. It is case-sensitive and matches plain substrings, not whole words. It is faster and simpler than a regular expression when you do not need patterns.
Syntax
str_replace(array|string $search, array|string $replace, string|array $subject, int &$count = null): string|array
Parameters
$search- The value to find, or an array of values.$replace- The replacement. If both$searchand$replaceare arrays, items are paired by position; missing replacements become empty strings.$subject- The string (or array of strings) to search in.$count- Optional variable that receives the number of replacements made.
Return value
A string (or an array, if $subject is an array) with the replacements applied. The original value is not changed.
str_replace() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Case-sensitive replacement with a counter
<?php
$text = "I like cats. Cats are great. cats!";
$result = str_replace("cats", "dogs", $text, $count);
echo $result . "\n";
echo "Replacements: $count\n";
Output:
I like dogs. Cats are great. dogs! Replacements: 2
2. Case-insensitive replacement with str_ireplace()
<?php
$text = "I like cats. Cats are great.";
echo str_ireplace("cats", "dogs", $text) . "\n";
Output:
I like dogs. dogs are great.
3. Replace several values at once
<?php
$template = "Hello {name}, your order #{id} has shipped.";
echo str_replace(["{name}", "{id}"], ["Alice", "1042"], $template) . "\n";
// Remove characters by replacing them with an empty string
echo str_replace([" ", "-"], "", "555-123 4567") . "\n";
Output:
Hello Alice, your order #1042 has shipped. 5551234567
4. Exact (whole-word) match
str_replace() also changes words that merely contain the search string. For whole-word matches use preg_replace() with \b word boundaries.
<?php
$text = "cat category concat cat";
echo str_replace("cat", "dog", $text) . "\n";
echo preg_replace('/\bcat\b/', 'dog', $text) . "\n";
Output:
dog dogegory condog dog dog category concat dog
Common mistakes and gotchas
- Chained replacements: with arrays, replacements run left to right on the already-modified string.
str_replace(["a", "b"], ["b", "c"], "ab")returns"cc", not"bc". Usestrtr($s, ["a" => "b", "b" => "c"])to replace in one pass. - Case:
str_replace()is case-sensitive; usestr_ireplace()to ignore case. - Whole words: there is no "exact match" flag; use
preg_replace('/\bword\b/', ...). - Return value: the function returns the new string. Calling
str_replace(...)without assigning the result does nothing.