我正在尝试编写PHP
代码,该代码找到HTML
的一部分并将其替换为另一个。
我的起点和终点是HTML
代码中的<!--top-index-start--> and <!--top-index-end-->
。
在PHP
代码找到它并从ckeditor
表单文本区替换为HTML
代码后,它再也找不到它了。
$pattern = '/<!--top-index-start-->(.*?)<!--top-index-end-->/';
$replacement = '<!--top-index-start-->' . $_POST['editor1'] . '<!--top-index-end-->';
$indexcontent = preg_replace($pattern, $replacement, $indexcontent);
你说的it cant find it anymore
是指你找不到<!--top-index-start-->
和<!--top-index-end-->
之间的内容吗?
当然,你已经把它完全换掉了。在我看来,你把抓人组弄反了。试试这个:
$regex = "~(<!--top-index-start-->).*?(<!--top-index-end-->)~";
$replacement = "'1".$_POST['editor1']."'2";
$indexcontent = preg_replace($regex, $replacement, $indexcontent);
regex中的捕获括号捕获第1组和第2组的顶部和结束分隔符。在替换字符串中,您将它们引用为'1
和'2
来构建替换。