程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php 只替換第一次出現的字符串

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

編輯:關於PHP編程

在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, '@');
        //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('[email protected]');        //輸出-->****[email protected]
    //show_email_2('[email protected]');        //輸出-->****[email protected]
    show_email_2('[email protected]');    //輸出-->61****[email protected]

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

$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即可實例了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved