Latest web development tutorials

PHP str_ireplace() 函數

PHP String 參考手冊 PHP String參考手冊

實例

把字符串"Hello world!" 中的字符"WORLD"(不區分大小寫)替換成"Peter":

<?php
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";
?>

運行實例»

實例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));
?>

運行實例»


PHP String 參考手冊 PHP String參考手冊