兩種方法:1、用preg_replace()將匹配字符替換為空字符,語(yǔ)法“preg_replace('/指定字符/i','',$str)”。2、用preg_filter(),語(yǔ)法“preg_filter('/字符/i','',$str)”。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php利用正則匹配某個(gè)字符并刪除的兩種方法
方法1:使用preg_replace()進(jìn)行正則替換
preg_replace() 函數(shù)可以執(zhí)行正則表達(dá)式的搜索和替換
只需要利用preg_replace()執(zhí)行正則表達(dá)式搜索指定字符并將其替換為空字符即可。
<?php header('content-type:text/html;charset=utf-8'); $str = '1132hell0 2313'; $pattern = '/l/i'; $replacement = ''; echo preg_replace($pattern, $replacement, $str); ?>
方法2:使用preg_filter()進(jìn)行正則替換
preg_filter()和preg_replace() 函數(shù)一樣,可以執(zhí)行正則表達(dá)式的搜索和替換。
只需執(zhí)行正則表達(dá)式搜索指定字符并將其替換為空字符即可。
<?php header('content-type:text/html;charset=utf-8'); $str = '1132hell0 2313'; echo "原字符串:".$str."<br>"; $pattern = '/3/i'; $replacement = ''; echo "處理后:".preg_filter($pattern, $replacement, $str); ?>
說(shuō)明: preg_replace() 和 preg_filter() 的區(qū)別
preg_filter() 函數(shù)只返回匹配成功的結(jié)果,而 preg_replace() 返回所有結(jié)果,不管是否匹配成功。
推薦學(xué)習(xí):《PHP視頻教程》