PHP preg_replace正在取代太多

时间:2014-08-01 13:31:36

标签: php preg-replace

代码:

$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/BEGIN (.*?) END/","XD",$string);

返回:ABCD XD ABCD,但我想返回ABCD BEGIN XD END ABCD

如何正确地做到这一点?

3 个答案:

答案 0 :(得分:8)

你可以使用积极的lookbehind和lookahead:

$result = preg_replace("/(?<=BEGIN )(.*?)(?= END)/","XD",$string);

答案 1 :(得分:0)

您可以使用它,如下所示

$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/LOL/","XD",$string);

答案 2 :(得分:0)

您可以使用多个捕获组并在替换中重新插入一些内容:

<?php

$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/(BEGIN\s)(.*)(\sEND)/","$1XD$3",$string);
//Output is: ABCD BEGIN XD END ABCD
?>