我有一个完全可重复的示例,它演示了PHP preg_replace
函数的奇怪行为。所以,我有两个包含此类内容的文件:
//new.txt
<!-- start -->Replacement 2\1<!-- end -->
//before.txt
<!-- start -->Text to replace<!-- end -->
当我这样做时:
$regex = "`<!-- start -->(.*?)<!-- end -->`";
$replacement = file_get_contents("new.txt");
$target = file_get_contents("before.txt");
$after = preg_replace($regex, $replacement, $target);
echo $after;
打印:
<!-- start -->Replacement 2Text to replace<!-- end -->
这确实是不正确的。但是当我这样做时:
$regex = "`<!-- start -->(.*?)<!-- end -->`";
$replacement = "<!-- start -->Replacement 2\1<!-- end -->";
$target = "<!-- start -->Text to replace<!-- end -->";
$after = preg_replace($regex, $replacement, $target);
echo $after;
打印:
<!-- start -->Replacement 2<!-- end -->
哪个更正确(但是,正如你所看到的,最后一个&#34; \ 1&#34;消失了)。顺便说一句,如果我删除&#34; \ 1&#34;,两个例子都开始正常工作。那么,我该如何解决呢?