在php中替換字串我們都會使用到str_replace函數了,此函數還可以使用正則,下面小編來給大家介紹一下替換字串中的一些字元或替換第一次出現的字元執行個體。
現在有個需求:字串A與字串B,字串B中包含字串A,利用字串A將字串B中的A替換成其他字串或刪除。
利用PHP函數,str_ireplace() 與 str_replace() 可以做到。
一、str_ireplace(find,replace,string,count) 函數使用一個字串替換字串中的另一些字元(該函數對大小寫不敏感)。
例如:
| 代碼如下 |
複製代碼 |
header(“Content-Type: text/html; charset=utf-8"); // 防止中文亂碼 $str_1 = '郭g碗w瓢p盆p'; $str_2 = '?潘?'; $str_3 = 'PHP 替換字串中的一些字串-郭G碗w瓢p盆P'; $str = str_ireplace($str_1,$str_2,$str_3); echo $str; // 輸出:PHP 替換字串中的一些字串-?潘 ?> |
二、str_replace(find,replace,string,count) 函數使用一個字串替換字串中的另一些字元(該函數對大小寫敏感)。
(參數與描述同 str_ireplace() 函數)
| 代碼如下 |
複製代碼 |
header(“Content-Type: text/html; charset=utf-8"); // 防止中文亂碼 $str_1_s = '郭g碗w瓢p盆p'; $str_1_b = '郭G碗w瓢p盆P'; $str_2 = '?潘?'; $str_3 = 'PHP 替換字串中的一些字串-郭G碗w瓢p盆P'; $str_s = str_replace($str_1_s,$str_2,$str_3).'
'; $str_b = str_replace($str_1_b,$str_2,$str_3); echo $str_s; // 無法尋找到,輸出原字串 echo $str_b; // 被正確替換 // $str_s 輸出:PHP 替換字串中的一些字串-郭G碗w瓢p盆P // $str_b 輸出:PHP 替換字串中的一些字串-?潘 ?> |
上面要替換肯定全部替換了,我如果想只替換第一次出現的字元呢
很多人想到了用str_replace()函數,看看這個函數的使用是不是我們要的
str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
不小心還真以為是我們想要的呢,最後那個參數是返回替換髮生的總次數,它是一個引用變數,而不是我要想要的指定它將替換幾次,所以用str_replace()是不行的
preg_replace()是可以實現的,可惜用了正則,
| 代碼如下 |
複製代碼 |
$str=preg_replace('/abc/','xyz',$str,1); echo $str; |
有沒有不用正則的,嗯可以這樣
| 代碼如下 |
複製代碼 |
$replace='xyz'; if(($position=strpos($str,$replace))!==false){ $leng=strlen($replace); $str=substr_replace($str,'xyz',$position,$leng); } echo $str; |
http://www.bkjia.com/PHPjc/632792.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/632792.htmlTechArticle在php中替換字串我們都會使用到str_replace函數了,此函數還可以使用正則,下面小編來給大家介紹一下替換字串中的一些字元或替換第一...