Detailed explanation of four uses of PHP string replacing str_replace of function

  • 2021-08-10 06:58:31
  • OfStack

In this article, I will share four uses of replacing str_replace () function with PHP string, which are as follows:

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

This function returns 1 string or array. This string or array is the result of replacing all search in subject with replace.

1, $search, string to replace, or array

2. $replace, the string or array to be replaced

3. $subject, the queried string or array

4, $count, optional, if specified, will be set to the number of replacements

5. Return value: This function returns the replaced array or string (newly generated)


<?php
  // Instances 1 String replacement string 
  $str1 = str_replace("red","black","red green yellow pink purple");
  echo $str1."";  // The output is black green yellow pink purple
?>
<?php
  // Instances 2 Replacing array key values with strings 
  $arr = array("blue","red","green","yellow");
  $str1 = str_replace("red","pink",$arr,$i);
  print_r($str1);
?>
<?php
  // Instances 3 Array for Array, Mapping for Array 
  $arr1 = array("banana","orange");
  $arr2 = array("pitaya","tomato");
  $con_arr = array("apple","orange","banana","grape");
  $con_rep = str_replace($arr1,$arr2,$con_arr,$count);
  print_r($con_rep);
?>
<?php
  // Instances 4 : For example $search Is an array, $replace Is a string 
  $search = array("banana","grape");
  $replace = "tomato";
  $arr = array("banana","apple","orange","grape");
  $new_arr = str_replace($search,$replace,$arr,$count);
  print_r($new_arr);
?>

Summarize


Related articles: