PHP String 參考手冊
執行個體
把 "Hello" 替換成 "world":
<?php
echo substr_replace("Hello","world",0);
?>
定義和用法
substr_replace() 函數把字元串的一部分替換為另一個字元串。
注釋:如果 start 參數是負數且 length 小于或者等于 start,則 length 為 0。
注釋:該函數是二進制安全的。
文法
substr_replace(string,replacement,start,length)
參數 | 描述 |
---|---|
string | 必需。規定要檢查的字元串。 |
replacement | 必需。規定要插入的字元串。 |
start | 必需。規定在字元串的何處開始替換。
|
length | 可選。規定要替換多少個字元。預設是與字元串長度相同。
|
技術細節
傳回值: | 傳回被替換的字元串。如果 string 是一個數組,則傳回數組。 |
---|---|
PHP 版本: | 4+ |
更新日志: | 自 PHP 4.3.3 起,所有參數都接受數組。 |
更多執行個體
執行個體 1
從字元串的第 6 個位置開始替換(把 "world" 替換成 "earth"):
echo substr_replace("Hello world","earth",6);
執行個體 2
從字元串結尾的第 5 個位置開始替換(把 "world" 替換成 "earth"):
echo substr_replace("Hello world","earth",-5);
執行個體 3
在 "world" 開頭插入 "Hello":
echo substr_replace("world","Hello ",0,0);
執行個體 4
一次性替換多個字元串。把每個字元串中的 "AAA" 替換成 "BBB":
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
PHP String 參考手冊