How to replace multiple strings in PHP?

In PHP, you can use the str_replace function to replace multiple strings. The function takes three parameters: the string to be replaced, the string to replace it with, and the string to perform the replacement operation on.

Here is the sample code:

$search = array("apple", "banana", "orange");
$replace = array("fruit1", "fruit2", "fruit3");
$string = "I like apple, banana, and orange.";

$result = str_replace($search, $replace, $string);
echo $result;

The output result is:

I like fruit1, fruit2, and fruit3.

In the code above, we define an array $search to store the strings to be replaced, an array $replace to store the strings to replace them with, and a variable $string to hold the string that needs to be replaced. We then use the str_replace function to replace the strings in the $search array with the corresponding strings in the $replace array, and assign the result to the variable $result. Finally, we output the value of the $result variable.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds