示例:
string1="ah ah I love you ah ah ah ah";
更换后:
string1="ah ah I love you ah thank you ah ah";
上述第四位的'啊'应该被'谢谢'
取代我不知道如何通过PHP编写上面的任务。你能救我吗?
答案 0 :(得分:5)
$string = "ah ah I love you ah ah ah ah";
echo preg_replace_callback('/ah/', function($m) {
static $count = 0;
if(++$count == 4) return 'thank you';
else return $m[0];
}, $string);
工作原理:每次ah
匹配回调函数都会被调用。静态$count
变量增加,当它是第四个匹配时,它返回替换字符串,否则返回最初匹配的字符串。
答案 1 :(得分:1)
非正则表达式。
$string = "ah ah I love you ah ah ah ah";
// search for the 4th 'ah'
$pos = 0;
for($i = 0; $i < 4; $i++){
$pos = strpos($string, 'ah', $pos);
$pos++;
}
// substring before the found, the replacement, and after the found
$result = substr($string, 0, $pos-1).'thank you'.substr($string, $pos+1);