str_replace() function in PHP || PHP str_replace function

str_replace() function in php


PHP str_replace() function is used to replace the part of a string to another string. If the string has occurred more than one time inside the main string then all occurrence is replaced. It is an inbuilt function of PHP.




  • $find represents the value to be searched into the main string. It can be either array or string. It is a required parameter.
  • $replace represents the value that is replaced with $find. It can also be either array or string. It is required.
  • $string is the main string on which all operations to be performed. It is also required.
  • $count is an optional parameter which counts the number of replacements

There are some rules which specify the working of this function.

  • If $find and $replace both are arrays then every element of $find is searched into the $string and replaced by the corresponding values in $replace.
  • If the $replace parameter is a string and $find is an array then every element of $find replaced by $replace string.

The return type of this function is either array or string depends on the type of $string.

Example 1:

$arr = array("apple","mango","banana","grapes");
echo "<pre>";
echo "Old array is : <br>";
echo "<br> New array is : <br>";
echo "<br> Number of replacement is :<strong>$count</strong>";


Example 2:

$str="Ram and shyam are good friends.";
echo "Old string is :<strong>$str</strong><br>";
echo "After replacement string is :<strong>$mod_str</strong>";


Best WordPress Hosting


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price

Leave a Reply

    Waiting for your comments