首頁  >  文章  >  後端開發  >  php怎麼刪除字串中的指定子字串

php怎麼刪除字串中的指定子字串

青灯夜游
青灯夜游原創
2021-10-14 17:59:342357瀏覽

方法:1、利用str_replace()以區分大小寫的方式刪除,語法「str_replace(子字串,'',字串)」;2、利用str_ireplace()以不區分大小寫的方式刪除,語法“str_ireplace(子字串,'',字串)”。

php怎麼刪除字串中的指定子字串

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

在php中,想要刪除字串中的指定子字串,可以透過對一個字串中的指定子字串進行替換,將其替換成空字串''即可。

而取代指定子字串,可以使用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
只需要將replace參數值設為空字串

''即可。

範例1:利用str_replace()函數移除指定子字串「hello」

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;hello,world,Hello,World&#39;;
$replace = &#39;&#39;;
$search = &#39;hello&#39;;
echo str_replace($search, $replace, $str);
?>

輸出結果:

php怎麼刪除字串中的指定子字串

範例2:利用str_ireplace()函數去除指定子字串「hello」

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;hello,world,Hello,World&#39;;
$replace = &#39;&#39;;
$search = &#39;hello&#39;;
echo str_ireplace($search, $replace, $str);
?>

輸出結果:

php怎麼刪除字串中的指定子字串##推薦學習:《

PHP影片教學

以上是php怎麼刪除字串中的指定子字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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