国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

php 只替換第一次出現的字符串

2024-05-04 21:57:01
字體:
來源:轉載
供稿:網友

在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位,代碼如下:

  1. function show_email_2($string){ 
  2.         $first = strpos($string'@'); 
  3.         //var_dump($first); 
  4.         if($first==1){ 
  5.             $string = '****'.$string
  6.         } 
  7.         if($first>1 && $first<=5){ 
  8.             $string = substr_replace($string,'****',0,$first-1);             
  9.         } 
  10.         if($first>5){ 
  11.             $string = substr_replace($string,'****',$first-5,4); 
  12.         } 
  13.          
  14.         var_dump($string); 
  15.         return $string
  16.     } 
  17.     //show_email_2('22@163.com');        //輸出-->****2@163.com 
  18.     //show_email_2('22@22.com');        //輸出-->****2@22.com 
  19.     show_email_2('6123456@163.com');    //輸出-->61****6@163.com 

有沒有不用正則的,嗯可以這樣

  1. $replace='xyz';  
  2. if(($position=strpos($str,$replace))!==false){  
  3.      $leng=strlen($replace);  
  4.     $str=substr_replace($str,'abc',$position,$leng);  
  5. }  
  6. echo $str

如果我想替換到指定次數可參考下面方法,代碼如下:

  1. <?php  
  2. /*  
  3.  * $text是輸入的文本;  
  4.  * $word是原來的字符串;  
  5.  * $cword是需要替換成為的字符串;  
  6.  * $pos是指$word在$text中第N次出現的位置,從1開始算起  
  7.  * */  
  8. function changeNstr($text,$word,$cword,$pos=1){  
  9. $text_array=explode($word,$text);  
  10. $num=count($text_array)-1;  
  11. if($pos>$num){  
  12. return "the number is too big!or can not find the $word";  
  13. }  
  14. $result_str='';  
  15. for($i=0;$i<=$num;$i++){  
  16. if($i==$pos-1){  
  17. $result_str.=$text_array[$i].$cword;  
  18. }else{  
  19. $result_str.=$text_array[$i].$word;} 
  20. return rtrim($result_str,$word);  
  21. }  
  22. $text='hello world hello pig hello cat hello dog hello small boy';  
  23. $word='hello';  
  24. $cword='good-bye';  
  25. echo changeNstr($text,$word,$cword,3);  
  26. //輸出:hello world hello pig good-bye cat hello dog hello small boy  
  27. ?> 

實例都很好理解,如果你不想深入了解我們直接使用str_replace即可實例了.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜昌市| 永修县| 纳雍县| 丹棱县| 丰台区| 防城港市| 松潘县| 民权县| 清水县| 揭西县| 会宁县| 长汀县| 榆树市| 军事| 鄯善县| 泉州市| 依兰县| 富顺县| 南宫市| 布拖县| 哈尔滨市| 临江市| 永胜县| 德钦县| 康乐县| 闸北区| 和林格尔县| 湘潭市| 兰州市| 西青区| 乐亭县| 祁连县| 洛浦县| 桐柏县| 景德镇市| 安陆市| 马关县| 甘肃省| 昌都县| 邛崃市| 信丰县|