Home > Backend Development > PHP Tutorial > Detailed explanation of str_replace() function in php

Detailed explanation of str_replace() function in php

autoload
Release: 2023-04-09 20:14:01
Original
3564 people have browsed it

The syntax of str_replace():

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

1.search and replace are all strings

<?php

$bodytag = str_replace("%body%", "black", "<body text=&#39;%body%&#39;>");
echo $bodytag; //输出:<body text=&#39;black&#39;>
?>
Copy after login

2. search is an array, replace is a string

<?php

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants;// 输出: Hll Wrld f PHP
?>
Copy after login

3. search and replace are both arrays

<?php
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
//输出:You should eat pizza, beer, and ice cream every day
?>
Copy after login

4. Contains the third Parameters

<?php
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;// 赋值: 2
?>
Copy after login

ps: search , the first group of replacement will affect the second group, as follows

$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)."<br/>";
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
Copy after login

Recommendation: php video tutorial php7 tutorial

The above is the detailed content of Detailed explanation of str_replace() function in php. 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