PHP str_replace() Function Tutorial

PHP provides the str_replace() function in order to replace characters or strings in a string. The str_replace() function can be also used to search in an array and replace string too. The replacement of the string occurs in every array element. The str_replace() function is case sensitive function where the uppercase and lowercase characters or letters are different and do not match. The str_replace() function is added to the PHP with the PHP version 4.

str_replace() Function Syntax

The str_replace() function accepts 4 parameters but only 3 of them are required. The str_replace() method has the following syntax.

  • FIND is used to specify the term we want to find or match. This parameter is required.
  • REPLACE is the term that will be replaced with the FIND. This parameter is required.
  • STRING is the string value or string variable which is searched in. This parameter is required.
  • COUNT specifies the number or replacement. By default, this parameter is not required and optional. If not specified all FIND occurrences are replaced with the REPLACE.

Replace String with str_replace() Function

The string replacement can be done by providing the FIND and REPLACE. But the STRING should be provided as an array. Multiple strings can be provided as array items where all of them can be replaced. If there is only one string a single item array can be also created.

   $string=array("I like I like");
   str_replace("like","am in love with",$string,$i);
   echo "Replacements: $i";

Leave a Comment