str_replace()
is a built-in PHP function used to replace all occurrences of a search string with a replacement string within another string (or array of strings).
Syntax:
str_replace(mixed $search, mixed $replace, mixed $subject, int &$count = null): string|array
Parameters:
$search
: The value(s) to be searched for (string or array).
$replace
: The value(s) to replace with (string or array).
$subject
: The input string or array.
$count
(optional): A variable passed by reference that will contain the number of replacements performed.
🔹 Simple Example:
$text = "Hello world!";
$newText = str_replace("world", "PHP", $text);
echo $newText; // Output: Hello PHP!
🔹 Replacing Multiple Values:
$text = "The quick brown fox jumps over the lazy dog.";
$search = ["quick", "brown", "lazy"];
$replace = ["slow", "red", "active"];
$newText = str_replace($search, $replace, $text);
echo $newText; // Output: The slow red fox jumps over the active dog.
🔹 Count Number of Replacements:
$text = "apple, apple, banana, apple";
$count = 0;
$newText = str_replace("apple", "orange", $text, $count);
echo $newText; // Output: orange, orange, banana, orange
echo $count; // Output: 3
🔹 Replacing in an Array:
$fruits = ["apple", "banana", "cherry"];
$newFruits = str_replace("banana", "orange", $fruits);
print_r($newFruits);
// Output:
// Array ( [0] => apple [1] => orange [2] => cherry )
🔸 Notes:
str_replace()
is case-sensitive. For case-insensitive replacement, use str_ireplace()
.
- If
$replace
has fewer values than $search
, it uses an empty string for the missing replacements.