查詢

str_replace()函式—用法及示例

「 替換字串中的部分內容 」


函式名:str_replace() 

適用版本:所有PHP版本(PHP 4,PHP 5,PHP 7) 

用法:替換字串中的部分內容

語法: str_replace($search, $replace, $subject, $count)

引數:

  • $search(必需):要查詢的字串或字串陣列。
  • $replace(必需):用於替換的字串或字串陣列。
  • $subject(必需):要在其中進行替換的字串或字串陣列。
  • $count(可選):替換的次數。預設為全部替換。

返回值:替換後的字串或字串陣列。

示例1:

$str = "Hello, World!";
$newStr = str_replace("World", "PHP", $str);
echo $newStr; // 輸出:Hello, PHP!

示例2:

$search = array("blue", "red", "green");
$replace = array("yellow", "purple", "orange");
$str = "The sky is blue, the rose is red, and the grass is green.";
$newStr = str_replace($search, $replace, $str);
echo $newStr; // 輸出:The sky is yellow, the rose is purple, and the grass is orange.

示例3:

$search = array("apple", "banana", "orange");
$replace = "fruit";
$str = "I like apple, banana, and orange.";
$newStr = str_replace($search, $replace, $str, $count);
echo $newStr; // 輸出:I like fruit, fruit, and fruit.
echo $count; // 輸出:3

注意事項:

  • 如果$search和$replace都是陣列,那麼$str也必須是陣列,函式將對每個元素進行替換。
  • 如果$search和$replace都是字串,那麼$str也必須是字串,函式將只替換第一個匹配項。
  • $count引數是可選的,如果提供了該引數,將返回替換的次數。
  • str_replace()函式是區分大小寫的,如果需要進行不區分大小寫的替換,可以使用str_ireplace()函式。
補充糾錯
上一個函式: stream_is_local()函式
下一個函式: str_repeat()函式
熱門PHP函式
分享連結