Home > Backend Development > PHP Problem > How to replace strings in php

How to replace strings in php

藏色散人
Release: 2023-03-07 20:54:01
Original
4830 people have browsed it

How to implement string replacement in php: first create a PHP sample file; then replace the string through the "str_replace("red","black","red green yellow pink purple");" method; Finally, the replacement result can be output through echo.

How to replace strings in php

The operating environment of this tutorial: Windows 7 system, PHP version 5.6. This method is suitable for all brands of computers.

Recommended: "PHP Video Tutorial"

PHP string replacement str_replace() function four usages

Parameters $search, the string or array to be replaced

Parameter $replace, the string or array to be replaced

Parameter $subject, the string or array to be queried

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

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

Example 1: String replaces string

  $str1 = str_replace("red","black","red green yellow pink purple");
  echo $str1."";  
  //输出结果为black green yellow pink purple
Copy after login

Example 2: String replaces array key value

  $arr = array("blue","red","green","yellow");
  $str1 = str_replace("red","pink",$arr,$i);
  print_r($str1);
Copy after login

Example 3: Array replaces array, mapping replaces

  $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);
Copy after login

Example 4 : If $search is an array and $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);
Copy after login

For more programming-related knowledge, please visit: Programming Learning Course! !

The above is the detailed content of How to replace strings in php. 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