當前位置: 首頁> 函數類別大全> substr_replace

substr_replace

替換字符串的子串
名稱:substr_replace
分類:字符串
所屬語言:php
一句話介紹:把字符串的一部分替換為另一個字符串。

定義和用法

substr_replace()函數把字符串的一部分替換為另一個字符串。

註釋:如果start參數是負數且length小於或者等於start ,則length為0。

註釋:該函數是二進制安全的。

實例

例子1

把"Hello" 替換成"world":

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

親自試一試

例子2

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

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

親自試一試

例子3

從字符串結尾的第5 個位置開始替換(把"world" 替換成"Shanghai"):

 <?php
echo substr_replace ( "Hello world" , "Shanghai" , - 5 ) ;
?>

親自試一試

例子4

在"world" 開頭插入"Hello":

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

親自試一試

例子5

一次性替換多個字符串。把每個字符串中的"AAA" 替換成"BBB":

 <?php
$replace = array ( "1: AAA" , "2: AAA" , "3: AAA" ) ;
echo implode ( "<br>" , substr_replace ( $replace , 'BBB' , 3 , 3 ) ) ;
?>

親自試一試

文法

substr_replace ( string , replacement , start , length )
參數 描述
string 必需。規定要檢查的字符串。
replacement 必需。規定要插入的字符串。
start

必需。規定在字符串的何處開始替換。

  • 正數- 在字符串中的指定位置開始替換
  • 負數- 在從字符串結尾的指定位置開始替換
  • 0 - 在字符串中的第一個字符處開始替換
length

可選。規定要替換多少個字符。默認是與字符串長度相同。

  • 正數- 被替換的字符串長度
  • 負數- 表示待替換的子字符串結尾處距離string末端的字符個數。
  • 0 - 插入而非替換
同類函數
  • 標記分割字符串 strtok

    strtok

    標記分割字符串
  • 單向字符串散列 crypt

    crypt

    單向字符串散列
  • 返回使用htmlspecialchars() 和htmlentities() 後的轉換錶 get_html_translation_table

    get_html_translation_table

    返回使用htmlspecialchars
  • 根據指定格式解析輸入的字符 sscanf

    sscanf

    根據指定格式解析輸入的字符
  • 查找指定字符在字符串中的最後一次出現 strrchr

    strrchr

    查找指定字符在字符串中的最後一次出現
  • 查找字符串的首次出現 strstr

    strstr

    查找字符串的首次出現
  • 計算子字符串出現次數 substr_count

    substr_count

    計算子字符串出現次數
  • 二進制安全比較字符串(從偏移位置比較指定長度) substr_compare

    substr_compare

    二進制安全比較字符串(從偏移位置比較指定
熱門文章