Saturday, 20 May 2017 14:13

Using PHP str_replace() Function

The str_replace()  function is used to replace a character with another character in PHP.



find = Value to search in the string 
replace = Value to replace the find with
string   =  String to be search
count = Variable that counts the number of replacements (Optional)


Example 1

In the example below we searched for the value Dublin and replaced with Galway

 $string = "Welcome to Dublin"; 
 echo str_replace("Dublin","Galway",$string);
Welcome to Galway

Replacing with empty value.

Example 2

We replaced the value Mr with an empty value 

$string = "Welcome home Mr Green"; $search = "Mr";
 $replace = "";
echo str_replace($search,$replace,$string);
Welcome home Green
Example 3

Searching an array and replacing its value with another value

$myarr = array("dog","cow","donkey","cat");
echo "<br>" . "Counter: $i"; //Count number of replacements

In this example, we search an array $myarr  for the value "cow" and replace it with the value "zebra". 

Array ( [0] => dog [1] => zebra [2] => donkey [3] => cat )
Counter: 1
Last modified on Monday, 29 May 2017 08:03
More in this category: PHP Date Function »

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.