2021-03-18

对php中str_replace()函数的详解

str_replace()的语法:

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

1.search ,replace都是字符串

<?php

$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
echo $bodytag; //输出:<body text='black'>
?>

2.search是数组 ,replace是字符串

<?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
?>

3.search ,replace都是数组

<?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
?>

4.含有第三个参数

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

ps: search ,replace的第一组替换会影响到第二组,如下

$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject)."<br/>";
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换

推荐:php视频教程 php7教程

以上就是对php中str_replace()函数的详解的详细内容,更多请关注php中文网其它相关文章!

php中文网最新课程二维码

  • 相关标签:php str_replace
  • 本文原创发布php中文网,转载请注明出处,感谢您的尊重!
  • https://www.php.cn/php-weizijiaocheng-472542.html

    发表回复

    Your email address will not be published. Required fields are marked *