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中str_replace()函數的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!