Detailed explanation of str_replace() substring replacement function

autoload
Release: 2023-03-09 13:12:01
Original
3630 people have browsed it

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 = ?   )
Copy after login
  • $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;
?>
Copy after login
输出:Chinese php.com is better,经过1次替换后,变为:Chinese php.cn is better
Copy after login

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);
Copy after login
输出:F
Copy after login

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!

Related labels:
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