reg表达式匹配任何html

时间:2014-06-07 20:44:02

标签: php html regex

我正在尝试编写PHP代码,找到HTML的一部分并将其替换为另一个代码。
我的起点和终点在<!--top-index-start--> and <!--top-index-end-->代码中为HTMLPHP代码找到它并使用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);  

1 个答案:

答案 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以构建替换。