首頁  >  文章  >  後端開發  >  php怎麼進行字串替換

php怎麼進行字串替換

青灯夜游
青灯夜游原創
2022-03-08 19:27:1514668瀏覽

字串替換方法:1、使用str_replace()函數,語法「str_replace(查找值,替換值,字串)」;2、使用substr_replace()函數,語法「substr_replace(字串,替換值,開始位置,替換長度)」。

php怎麼進行字串替換

本教學操作環境:windows7系統、PHP7.1版、DELL G3電腦

在 PHP 中,可以對一個字串中的特定字元或子字串進行替換,這是非常常用的功能。

php進行字串替換

#方法1:str_ireplace() 和str_replace() 函數

#str_ireplace() 和str_replace 使用新的字串取代原來字串中指定的特定字串,str_replace 區分大小寫,str_ireplace() 不區分大小寫,兩者語法相似。

str_replace(find,replace,string,count)
str_ireplace(find,replace,string,count)
參數 描述
find 必要。規定要找的值。
replace 必要。規定替換 find 中的值的值。
string 必要。規定被搜尋的字串。
count #可選。對替換數進行計數的變數。

範例:

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;hello,world,Hello,world&#39;;
echo "原字符串:".$str."<br>";

$search = &#39;hello&#39;;
$replace = &#39;hi&#39;;

echo "<br>替换字符串:<br>";
echo str_replace($search, $replace, $str)."<br>";
echo str_ireplace($search, $replace, $str)."<br>";
?>

php怎麼進行字串替換

#方法2:substr_replace() 函數

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

substr_replace() 函數的語法如下:

substr_replace(string,replacement,start,length)
##string必要。規定要插入的字串。 start
#參數 描述
  • 必要。規定要檢查的字串。
  • replacement
  • #必要。規定在字串的何處開始替換。
  • 正數- 在字串的指定位置開始
  • 負數- 在從字串結尾的指定位置開始
0 - 在字串中的第一個字符處開始

length

可選。規定要替換多少個字元。預設是與字串長度相同。

正數- 被替換的字串長度######負數- 從字串末端開始的被替換字元數######0 - 插入而非替換###### ################範例:###
<?php
$str = &#39;hello,world,hello,world&#39;;
$replace = &#39;hi&#39;;
echo substr_replace($str, $replace, 0,5);
?>
###以上程式碼的執行結果為:###
hi,world,hello,world
###推薦學習:《###PHP影片教學# ##》###

以上是php怎麼進行字串替換的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn