Home  >  Article  >  Backend Development  >  Detailed explanation of str_replace() substring replacement function

Detailed explanation of str_replace() substring replacement function

autoload
autoloadOriginal
2021-05-07 10:12:443525browse

In the last article, we introduced "Converting php variables to json format data". In this article, we will introduce strings. String is a common data type that is operated during php. For substring operations, php has built-in str_replace(). This article will show you Let’s take a look. First, let's take a look at the syntax of the str_replace() function.

str_replace   ( mixed $search   , mixed $replace   , mixed $subject   , int &$count = ?   )
  • $search: The target that needs to be searched

  • $replace: The value that needs to be replaced with the target

  • $subject: String or array to be processed

  • $count: Optional, the number of times replacement occurs

  • Return value: This function returns the replaced array or string.

Code example:

1. The parameters are all strings

<?php
$str="Chinese php.com is better";
$str2 = str_replace("com", "cn",$str,$count);
echo $str.",经过".$count."次替换后,变为:".$str2;
?>
输出:Chinese php.com is better,经过1次替换后,变为:Chinese php.cn is better

2. The parameters are all arrays

<?php
$search  = array(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;);
$replace = array(&#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;);
$subject = &#39;A&#39;;
echo str_replace($search, $replace, $subject);
输出:F

Recommendation: 2021 Summary of PHP interview questions (Collection)》《php video tutorial

The above is the detailed content of Detailed explanation of str_replace() substring replacement function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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