您好,欢迎访问一九零五行业门户网

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

比如有一个字符串:$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面试题: http://phpmst.com/
$num){ return the number is too big!or can not find the $word; } $result_str=''; for($i=0;$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?>
复制代码
其它类似信息

推荐信息