首頁  >  文章  >  後端開發  >  php中str_replace()函數的詳解

php中str_replace()函數的詳解

autoload
autoload原創
2021-03-18 16:18:473513瀏覽

    str_replace()的語法:

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

1.search  ,replace都是字串
##

<?php

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

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(&#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 替换

建議:

php影片教學 php7教學#

以上是php中str_replace()函數的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn