PHP substr_replace() 函數

PHP String 參考手冊 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 必需。規定在字串的何處開始替換。
  • 正數 - 在字串的指定位置開始
  • 負數 - 在從字串結尾的指定位置開始
  • 0 - 在字串中的第一個字元處開始
length 可選。規定要替換多少個字元。默認是與字串長度相同。
  • 正數 - 被替換的字串長度
  • 負數 - 從字串末端開始的被替換字元數
  • 0 - 插入而非替換

技術細節

返回值: 返回被替換的字串。如果 string 是一個數組,則返回數組。
PHP 版本: 4+
更新日誌: 自 PHP 4.3.3 起,所有參數都接受數組。


更多實例

實例 1

從字串的第 6 個位置開始替換(把 "world" 替換成 "earth"):

<?php
echo substr_replace("Hello world","earth",6);
?>


實例 2

從字串結尾的第 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 參考手冊 PHP String 參考手冊