Home > Backend Development > PHP Tutorial > What are the methods of php string replacement str_replace() function? (four types)

What are the methods of php string replacement str_replace() function? (four types)

不言
Release: 2023-04-03 21:30:01
Original
2093 people have browsed it

What this article brings to you is what are the methods of replacing str_replace() function in PHP strings? (Four types) have certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article will share with you 4 ways to use the PHP string replacement str_replace() function. The specific content is as follows:

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

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

1. $search, the string or array to be replaced

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

3. $subject, The string or array being queried

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

  //实例一:字符串替换字符串

  $str1 = str_replace("red","black","red green yellow pink purple");

  echo $str1."";  //输出结果为black green yellow pink purple

?>

<?php

  //实例二:字符串替换数组键值

  $arr = array("blue","red","green","yellow");

  $str1 = str_replace("red","pink",$arr,$i);

  print_r($str1);

?>

<?php

  //实例三:数组替换数组,映射替换

  $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

  //实例四:如$search为数组,$replace为字符串时

  $search = array("banana","grape");

  $replace = "tomato";

  $arr = array("banana","apple","orange","grape");

  $new_arr = str_replace($search,$replace,$arr,$count);

  print_r($new_arr);

?>
Copy after login

Related recommendations:

php function substring replacement str_replace

Introduction to the use of php string replacement str_replace() function

The above is the detailed content of What are the methods of php string replacement str_replace() function? (four types). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template