Reg表达式匹配任何html


reg expression to match any html

我正在尝试编写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来构建替换。

相关文章: