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.

Syntax

str_replace(search,replace,string,count);

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

 
<?php 
 $string = "Welcome to Dublin"; 
 echo str_replace("Dublin","Galway",$string);
?>
 
Result
 
Welcome to Galway
 


Replacing with empty value.

Example 2

We replaced the value Mr with an empty value 

<?php 
$string = "Welcome home Mr Green"; $search = "Mr";
 $replace = "";
echo str_replace($search,$replace,$string);
?>
Result
 
Welcome home Green
 
Example 3

Searching an array and replacing its value with another value

<?php 
$myarr = array("dog","cow","donkey","cat");
print_r(str_replace("cow","zebra",$myarr,$i));
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". 

Result
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.