PHP str_replace() Function
PHP str_replace() Syntax
str_replace(array|string $search, array|string $replace, string|array $subject, int &$count = null): string|array
PHP str_replace() Basic examples
$text = "Hello world";
echo str_replace("world", "PHP", $text);
Hello PHP
Replaces a substring with another string.
$text = "foo bar foo";
echo str_replace("foo", "baz", $text);
baz bar baz
Replaces all occurrences, not just the first.
$text = "abc";
echo str_replace("x", "y", $text);
abc
If the search string is not found, the original string is returned.
PHP str_replace() Real-world usage
$filename = "report final.pdf";
echo str_replace(" ", "_", $filename);
report_final.pdf
Normalizes filenames by replacing spaces.
$input = "<script>alert(1)</script>";
echo str_replace(["<", ">"], ["<", ">"], $input);
<script>alert(1)</script>
Performs basic escaping by replacing multiple values.
PHP str_replace() Edge cases
$text = "aaaa";
echo str_replace("aa", "b", $text);
bb
Replacements do not overlap.
$text = "test";
echo str_replace("", "x", $text);
test
An empty search string results in no changes.
PHP str_replace() Common mistakes
Expecting case-insensitive replacement
str_replace() is case-sensitive.
echo str_replace("hello", "Hi", "Hello");
echo str_ireplace("hello", "Hi", "Hello");
Use str_ireplace() for case-insensitive replacements.
PHP str_replace() Frequently Asked Questions
What does str_replace() do in PHP?
str_replace() replaces all occurrences of a search string with a replacement string.
Is str_replace() case-sensitive?
Yes, str_replace() is case-sensitive. Use str_ireplace() for case-insensitive replacement.
Can str_replace() replace multiple values at once?
Yes, you can pass arrays for search and replace parameters to replace multiple values in one call.
Does str_replace() modify the original string?
No, str_replace() returns a new string and does not modify the original variable unless reassigned.
What happens if the search value is not found?
str_replace() returns the original string unchanged if no matches are found.
Can str_replace() work with arrays?
Yes, str_replace() can operate on arrays of strings and return an array of results.
What is the difference between str_replace() and preg_replace()?
str_replace() performs simple string replacement, while preg_replace() uses regular expressions.
Does str_replace() replace overlapping matches?
No, str_replace() replaces non-overlapping occurrences from left to right.
Can str_replace() count replacements?
Yes, you can pass a fourth parameter to store the number of replacements made.
Is str_replace() fast?
Yes, str_replace() is a fast built-in function suitable for most string replacement tasks.
What is a real-world use case of str_replace()?
str_replace() is commonly used to sanitize input, replace placeholders, or clean strings.
How to remove a substring using str_replace()?
Replace the substring with an empty string, for example str_replace("text", "", $string).