PHP str_replace() 函數
實例
把字串 "Hello world!" 中的字元 "world" 替換成 "Peter":
<?php
echo str_replace("world","Peter","Hello world!");
?>
echo str_replace("world","Peter","Hello world!");
?>
定義和用法
str_replace() 函數替換字串中的一些字元(區分大小寫)。
該函數必須遵循下列規則:
- 如果搜索的字串是一個數組,那麼它將返回一個數組。
- 如果搜索的字串是一個數組,那麼它將對數組中的每個元素進行查找和替換。
- 如果同時需要對某個數組進行查找和替換,並且需要執行替換的元素少於查找到的元素的數量,那麼多餘的元素將用空字元串進行替換。
- 如果是對一個數組進行查找,但只對一個字串進行替換,那麼替代字串將對所有查找到的值起作用。
注釋:該函數是區分大小寫的。請使用 str_ireplace() 函數執行不區分大小寫的搜索。
注釋:該函數是二進位安全的。
語法
str_replace(find,replace,string,count)
參數 | 描述 |
---|---|
find | 必需。規定要查找的值。 |
replace | 必需。規定替換 find 中的值的值。 |
string | 必需。規定被搜索的字串。 |
count | 可選。一個變數,對替換數進行計數。 |
技術細節
返回值: | 返回帶有替換值的字串或數組。 |
---|---|
PHP 版本: | 4+ |
更新日誌: | 在 PHP 5.0 中,新增了 count 參數。 在 PHP 4.3.3 之前,該函數的 find 和 replace 參數都為數組時將會遇到麻煩,會引起空的 find 索引在內部指針沒有更換到 replace 數組上時被忽略。新的版本不會有這個問題。 自 PHP 4.0.5 起,大多數參數可以是一個數組。 |
更多實例
實例 1
使用帶有數組和 count 變數的 str_replace() 函數:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
實例 2
使用帶有需要替換的元素少於查找到的元素的 str_replace() 函數:
<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
