把"Hello" 替換成"world":
<?phpecho 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 起,所有參數都接受陣列。 |
從字串的第6 個位置開始替換(把"world" 替換成"earth"):
<?phpecho substr_replace("Hello world","earth",6);?>從字串結尾的第5 個位置開始替換(把"world" 替換成"earth"):
<?phpecho substr_replace("Hello world","earth",-5);?>在"world" 開頭插入"Hello":
<?phpecho substr_replace("world","Hello ",0,0);?>一次性替換多個字串。把每個字串中的"AAA" 替換成"BBB":
<?php$replace = array("1: AAA","2: AAA","3: AAA");echo implode("<br>",substr_replace($replace,'BBB',3,3)) ;?>