把字符串 "Hello world!" 中的字符 "world" 替換為 "Shanghai":
<?php echo str_replace("world","Shanghai","Hello world!"); ?>
str_replace() 函數(shù)以其他字符替換字符串中的一些字符(區(qū)分大小寫)。
該函數(shù)必須遵循下列規(guī)則:
注釋:該函數(shù)區(qū)分大小寫。請使用 str_ireplace() 函數(shù)執(zhí)行不區(qū)分大小寫的搜索。
注釋:該函數(shù)是二進制安全的。
str_replace(find,replace,string,count)
參數(shù) | 描述 |
---|---|
find | 必需。規(guī)定要查找的值。 |
replace | 必需。規(guī)定替換 find 中的值的值。 |
string | 必需。規(guī)定被搜索的字符串。 |
count | 可選。對替換數(shù)進行計數(shù)的變量。 |
返回值: | 返回帶有替換值的字符串或數(shù)組。 |
PHP 版本: | 4+ |
更新日志: |
在 PHP 5.0 中,新增了 count 參數(shù)。 在 PHP 4.3.3 之前,該函數(shù)的 find 和 replace 參數(shù)都為數(shù)組時將會遇到麻煩,會引起空的 find 索引在內(nèi)部指針沒有更換到 replace 數(shù)組上時被忽略。新的版本不會有這個問題。 自 PHP 4.0.5 起,大多數(shù)參數(shù)可以是一個數(shù)組。 |
使用帶有數(shù)組和 count 變量的 str_replace() 函數(shù):
<?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "替換數(shù):$i"; ?>
使用帶有需要替換的元素少于查找到的元素的 str_replace() 函數(shù):
<?php $find = array("Hello","world"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_replace($find,$replace,$arr)); ?>
如對本文有疑問,請?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會為你解答!! 點擊進入論壇
Powered by 365建站網(wǎng) RSS地圖 HTML地圖
copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號