在php中要替换串中指定字符我们一般会一次全部替换,如str_replace函数,但有时只想替换第一次出现的,像文章的关键词替换了,这个如果有100个不可能出现100次啊,我只想限制几次了,下面我来给各位介绍实现方法。

在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('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 
?>


上一篇:阿里巴巴排名查询工具

下一篇:一个使用jquery的一个图片延迟加载插件(这个感觉比较好)

评论列表
发表评论
称呼
邮箱
网址
验证码(*)
热评文章
相关阅读