- <?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://www.codesnippet.cn/detail/030720134416.html
来源: http://www.codesnippet.cn/detail/030720134416.html