龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php 替换字符串中第N次出现的字符,不用正则表达式

时间:2014-07-22 15:59来源:网络整理 作者:网络 点击:
分享到:
替换字符串中第N次出现的字符,不用正则表达式 比如有一个字符串:$a=#39;hello world hello pig hello cat hello dog hello small boy#39;;然后想将第3次出现的hello 改变成为good-bye,比如:#39;hello world

比如有一个字符串:$a='hello world hello pig hello cat hello dog hello small boy';

然后想将第3次出现的hello 改变成为good-bye,比如:

'hello world hello pig good-bye cat hello dog hello small boy';

这样的情况,我一时半会没找到PHP的内置函数,而且在要求不能使用正则表达式的情况下,就编写了这个简易的小函数,如果大家有好的内置函数推荐,欢迎留言:)

<?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
?>
//该片段来自于http://outofmemory.cn
精彩图集

赞助商链接