例
$str='這是字串我只替換ABC一次後面的ABC我不替換了,有沒有辦法實現。';
把第一個abc替換成xyz,由於要替換的字串是固定的,很多人想到了用str_replace()函數,看看這個函數的使用是不是我們要的
str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
不小心還真以為是我們想要的呢,最後那個參數是返回替換髮生的總次數,它是一個引用變數,而不是我要想要的指定它將替換幾次,所以用str_replace()是不行的
preg_replace()是可以實現的,可惜用了正則,
| 代碼如下 |
複製代碼 |
$str=preg_replace('/abc/','abc',$str,1); echo $str; |
例
顯示email為 從@前2位(含)開始向前隱藏4位
| 代碼如下 |
複製代碼 |
function show_email_2($string){ $first = strpos($string, '@'); //var_dump($first); if($first==1){ $string = '****'.$string; } if($first>1 && $first<=5){ $string = substr_replace($string,'****',0,$first-1); } if($first>5){ $string = substr_replace($string,'****',$first-5,4); } var_dump($string); return $string; } //show_email_2('22@163.com'); //輸出-->****2@163.com //show_email_2('22@22.com'); //輸出-->****2@22.com show_email_2('6123456@163.com'); //輸出-->61****6@163.com 有沒有不用正則的,嗯可以這樣 $replace='xyz'; if(($position=strpos($str,$replace))!==false){ $leng=strlen($replace); $str=substr_replace($str,'abc',$position,$leng); } echo $str; |
如果我想替換到指定次數可參考下面方法
| 代碼如下 |
複製代碼 |
<?php /* * $text是輸入的文本; * $word是原來的字串; * $cword是需要替換成為的字串; * $pos是指$word在$text中第N次出現的位置,從1開始算起 * */ function changeNstr($text,$word,$cword,$pos=1){ $text_array=explode($word,$text); $num=count($text_array)-1; if($pos>$num){ return "the number is too big!or can not find the $word"; } $result_str=''; for($i=0;$i<=$num;$i++){ if($i==$pos-1){ $result_str.=$text_array[$i].$cword; }else{ $result_str.=$text_array[$i].$word;} } return rtrim($result_str,$word); } $text='hello world hello pig hello cat hello dog hello small boy'; $word='hello'; $cword='good-bye'; echo changeNstr($text,$word,$cword,3); //輸出:hello world hello pig good-bye cat hello dog hello small boy ?> |
執行個體都很好理解,如果你不想深入瞭解我們直接使用str_replace即可執行個體了。