Replace Multiple Items In String Using PHP str_replace Function

By Faruque Ahamed Mollick

I have already shown in one of my posts how to replace a character of a string using the PHP str_replace() function. Here is the post – Replace A Character Of String Using PHP With Other Character.

Now in this tutorial, I am going to show you how to replace multiple items in a string using the same PHP str_replace() function.

Replace multiple items in string using PHP str_replace() function

There is an easy technique which can be used to replace multiple items or characters in a string and here also, we are going to use the str_replace() function. below is a simple example code snippet which shows you how to do it:

 $string = "You are NAME and Your are AGE years old. You live in CITY";
 $age_replace = str_replace("AGE","19",$string);
 $name_replace = str_replace("NAME","Rajesh",$age_replace);
 $cityname_replace = str_replace("CITY","Mumbai",$name_replace);
 echo $cityname_replace;

In the above example code, you can notice that we have used str_replace function to replace the text “AGE” into “19”. We have taken it inside a variable $age_replace and then again use str_replace function to replace the “NAME” text into “Rajesh”. We take it inside variable $name replace. At the end we replace the “CITY” text into “Mumbai”, take it inside variable $cityname_replace and displaying it on the web page.

Getting weather data from OpenWeatherMap API using PHP

Simple PHP Code To Detect Mobile Device

Now we have successfully replaced three items using the PHP str_replace() function. We have replaces “AGE”, “NAME” and “CITY”. Using the same process, you can replace more items as you want.

There is one important thing that you should always keep in mind is that str_replace() function is case sensitive.

Leave a Reply

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