php 只替換第一次出現的字符串
來源:程序員人生 發布時間:2013-12-04 09:55:35 閱讀次數:3764次
在php中要替換串中指定字符我們一般會一次全部替換,如str_replace函數,但有時只想替換第一次出現的,像文章的關鍵詞替換了,這個如果有100個不可能出現100次啊,我只想限制幾次了,下面我來給各位介紹實現方法。
例:$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, '@');
-
- 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('6123456@163.com');
有沒有不用正則的,嗯可以這樣
- $replace='xyz';
- if(($position=strpos($str,$replace))!==false){
- $leng=strlen($replace);
- $str=substr_replace($str,'abc',$position,$leng);
- }
- echo $str;
如果我想替換到指定次數可參考下面方法,代碼如下:
- <?php
-
-
-
-
-
-
- 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);
-
- ?>
實例都很好理解,如果你不想深入了解我們直接使用str_replace即可實例了.
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈