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