代码:
$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/BEGIN (.*?) END/","XD",$string);
返回:ABCD XD ABCD
,但我想返回ABCD BEGIN XD END ABCD
,
如何正确地做到这一点?
答案 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
?>