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

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

时间:2014-07-22 14:51来源: 作者: 点击:
分享到:
比如有一个字符串:$a=hello world hello pig hello cat hello dog hello small boy; br / 然后想将第3次出现的hello 改变成为good-bye,比如: br / hello world hello piggood-bye cat hello dog hello small boy; br / 这样的情
比如有一个字符串:$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/

<?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
?>
精彩图集

赞助商链接