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, usestr_ireplace()
.- If
$replace
has fewer values than$search
, it uses an empty string for the missing replacements.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.