在php中,可以利用substr_replace()函數(shù)來替換字符串后幾位字符,只需要將該函數(shù)的第三個參數(shù)設置為負值即可,語法為“substr_replace (字符串,替換值,-N)”,會從字符串倒數(shù)第N個字符開始替換剩下的全部字符,即么替換字符串后N位字符。
本教程操作環(huán)境:windows7系統(tǒng)、PHP8.1版、DELL G3電腦
在php中,可以利用substr_replace()函數(shù)來替換字符串后幾位字符。
substr_replace()函數(shù)可以從字符串指定位置開始替換指定個數(shù)的字符。
substr_replace(string,replacement,start,length)
參數(shù) | 描述 |
---|---|
string | 必需。規(guī)定要檢查的字符串。 |
replacement | 必需。規(guī)定要插入的字符串。 |
start | 必需。規(guī)定在字符串的何處開始替換。
|
length | 可選。規(guī)定要替換多少個字符。默認是與字符串長度相同。
|
substr_replace() 在字符串 string 的副本中將由 start 和可選的 length 參數(shù)限定的子字符串使用 replacement 進行替換。
如果 start 為正數(shù),替換將從 string 的 start 位置開始。如果 start 為負數(shù),替換將從 string 的倒數(shù)第 start 個位置開始。
如果設定了 length 參數(shù)并且為正數(shù),就表示 string 中被替換的子字符串的長度。如果設定為負數(shù),就表示待替換的子字符串結(jié)尾處距離 string 末端的字符個數(shù)。如果沒有提供此參數(shù),那么默認為 strlen(string)(字符串的長度)。當然,如果 length 為 0,那么這個函數(shù)的功能為將 replacement 插入 string 的 start 位置處。
示例:
<?php header('content-type:text/html;charset=utf-8'); $str = 'hello world!'; echo "原字符串:".$str."<br><br>"; $replace = 'AA'; echo "替換后2位字符:".substr_replace($str, $replace,-2)."<br>"; echo "替換后3位字符:".substr_replace($str, $replace,-3)."<br>"; echo "替換后4位字符:".substr_replace($str, $replace,-4)."<br>"; echo "替換后5位字符:".substr_replace($str, $replace,-5)."<br>"; ?>
推薦學習:《PHP視頻教程》