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
$replacehas fewer values than$search, it uses an empty string for the missing replacements.
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
