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

來源:互聯網
上載者:User

$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即可執行個體了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.