当前位置:编程学习 > php >>

php 只替换第一次出现的字符串

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

补充:Php教程,Php应用 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,