我正在尝试编写PHP
代码,找到HTML
的一部分并将其替换为另一个代码。
我的起点和终点在<!--top-index-start--> and <!--top-index-end-->
代码中为HTML
在PHP
代码找到它并使用HTML
表单textarea中的ckeditor
代码替换后,它无法再找到它。
$pattern = '/<!--top-index-start-->(.*?)<!--top-index-end-->/';
$replacement = '<!--top-index-start-->' . $_POST['editor1'] . '<!--top-index-end-->';
$indexcontent = preg_replace($pattern, $replacement, $indexcontent);
答案 0 :(得分:1)
按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);
<强>解释强>
正则表达式中的捕获括号将您的顶部和结尾分隔符捕获到第1组和第2组。在替换字符串中,您将这些引用为\1
和\2
以构建替换。