Web Development & WordPress

Efficiently Replacing Multiple Words in a String Using PHP

Here I have shown how to efficiently replace multiple words in a string using PHP’s str_replace function. In this example you can see how to modify text by swapping out specified words with new ones.

CODE:

<?php
$string  ="The dog was black in color, and the cat was white, the squirrel was grey in color ";
echo "Main String:<br>";
echo $string;
echo "<br>After replacing multiple words in main string :<br>";
$afterReplace = str_replace(array("black","white","grey"),array("chocolate","brown","darkgrey"),$string,$number);
echo $afterReplace;
echo "<br>Total Word Changed : ".$number;
?>

OUTPUT:

Main String:
The dog was black in color, and the cat was white, the squirrel was grey in color
After replacing multiple words in main string :
The dog was chocolate in color, and the cat was brown, the squirrel was darkgrey in color
Total Word Changed : 3

Leave a comment