3種方法:1、使用“str_replace("-",'',$str)”將“-”字符替換為空字符;2、用“preg_replace("/-/","",$str)”執(zhí)行正則表達式來查找“-”字符并將去除;3、用preg_filter()來去除。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php字符串去掉“-”字符的方法
方法1:使用str_replace()或str_replace() 函數
str_ireplace() 和 str_replace 使用新的字符串替換原來字符串中指定的特定字符串,str_replace 區(qū)分大小寫,str_ireplace() 不區(qū)分大小寫,兩者語法相似。
只需將“-
”字符替換為空字符''
即可。
<?php header('content-type:text/html;charset=utf-8'); $str="1-2-3-4-5-6-7-8"; echo "原字符串:".$str."<br><br>"; echo "去掉'-'字符后:<br>"; echo str_replace("-",'',$str)."<br>"; echo str_ireplace("-",'',$str)."<br>"; ?>
方法2:使用preg_replace()函數
preg_replace()函數可以配合正則表達式來查找全部“-”字符,并將其替換為空字符''即可。
<?php header('content-type:text/html;charset=utf-8'); $str="1-2-3-4-5-6-7-8"; echo "原字符串:".$str."<br><br>"; echo "去掉'-'字符后:".preg_replace("/-/", "", $str)."<br>"; ?>
方法3:使用preg_filter()函數
同樣,preg_filter()函數配合正則表達式來查找全部“-”字符,并將其替換為空字符''即可。
<?php header('content-type:text/html;charset=utf-8'); $str="1-2-3-4-5-6-7-8-9-"; echo "原字符串:".$str."<br><br>"; echo "去掉'-'字符后:".preg_filter("/-/", "", $str)."<br>"; ?>
推薦學習:《PHP視頻教程》