PHP substr_replace() 函數(shù)
PHP String 參考手冊
實例
把 "Hello" 替換成 "world":
<?php
echo substr_replace("Hello","world",0);
?>
運行實例 ?
定義和用法
substr_replace() 函數(shù)把字符串的一部分替換為另一個字符串。
注釋:如果 start 參數(shù)是負(fù)數(shù)且 length 小于或者等于 start,則 length 為 0。
注釋:該函數(shù)是二進制安全的。
語法
substr_replace(string,replacement,start,length)
參數(shù) | 描述 |
string | 必需。規(guī)定要檢查的字符串。 |
replacement | 必需。規(guī)定要插入的字符串。 |
start | 必需。規(guī)定在字符串的何處開始替換。 - 正數(shù) - 在字符串的指定位置開始
- 負(fù)數(shù) - 在從字符串結(jié)尾的指定位置開始
- 0 - 在字符串中的第一個字符處開始
|
length | 可選。規(guī)定要替換多少個字符。默認(rèn)是與字符串長度相同。 - 正數(shù) - 被替換的字符串長度
- 負(fù)數(shù) - 從字符串末端開始的被替換字符數(shù)
- 0 - 插入而非替換
|
技術(shù)細(xì)節(jié)
返回值: | 返回被替換的字符串。如果 string 是一個數(shù)組,則返回數(shù)組。 |
PHP 版本: | 4+ |
更新日志: | 自 PHP 4.3.3 起,所有參數(shù)都接受數(shù)組。 |
更多實例
實例 1
從字符串的第 6 個位置開始替換(把 "world" 替換成 "earth"):
<?php
echo substr_replace("Hello world","earth",6);
?>
運行實例 ? 實例 2
從字符串結(jié)尾的第 5 個位置開始替換(把 "world" 替換成 "earth"):
<?php
echo substr_replace("Hello world","earth",-5);
?>
運行實例 ? 實例 3
在 "world" 開頭插入 "Hello":
<?php
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 參考手冊