方法:1、利用str_replace()以區(qū)分大小寫的方式刪除,語法“str_replace(子串,'',字符串)”;2、利用str_ireplace()以不區(qū)分大小寫的方式刪除,語法“str_ireplace(子串,'',字符串)”。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
在php中,想要刪除字符串中的指定子串,可以通過對一個字符串中的指定子串進行替換,將其替換成空字符串''
即可。
而替換指定子串,可以使用str_ireplace() 和 str_replace 函數(shù),它們都會使用新的字符串替換原來字符串中指定的特定字符串,str_replace 區(qū)分大小寫,str_ireplace() 不區(qū)分大小寫,兩者語法相似:
str_replace(find,replace,string,count) str_ireplace(find,replace,string,count)
參數(shù) | 描述 |
---|---|
find | 必需。規(guī)定要查找的值。 |
replace | 必需。規(guī)定替換 find 中的值的值。 |
string | 必需。規(guī)定被搜索的字符串。 |
count | 可選。一個變量,對替換數(shù)進行計數(shù)。 |
只需要將replace參數(shù)值設置為空字符串''
即可。
示例1:利用str_replace()函數(shù)去除指定子串“hello”
<?php header("Content-type:text/html;charset=utf-8"); $str = 'hello,world,Hello,World'; $replace = ''; $search = 'hello'; echo str_replace($search, $replace, $str); ?>
輸出結果:
示例2:利用str_ireplace()函數(shù)去除指定子串“hello”
<?php header("Content-type:text/html;charset=utf-8"); $str = 'hello,world,Hello,World'; $replace = ''; $search = 'hello'; echo str_ireplace($search, $replace, $str); ?>
輸出結果:
推薦學習:《PHP視頻教程》