仅将自定义标记内的HTML /值替换一次

时间:2014-06-11 10:17:47

标签: php regex preg-replace

我想替换自定义HTML标记,例如:

<!-- {start %x%} -->Data<!-- {mid %x%} -->Data<!-- {end %x%} -->

替换只会发生一次。在下面的HTML中有两个自定义HTML标记。正确的正则表达式是什么。

$pattern_loop = "/\<\!\-\- \{start %x%\} \-\-\>(.*)" . 
"(\<\!\-\- \{mid %x%\} \-\-\>)(.*)\<\!\-\- \{end %x%\} \-\-\>/";
$html= '<!-- {start %x%} --><br />Your account must be approved before you can login. Once approved you can log in by using your email address and password by visiting our website or at the following URL:<br /><!-- {mid %x%} --><br />Your account has now been created and you can log in by using your email address and password by visiting our website or at the following URL:<br /><!-- {end %x%} --><br /><!-- {start %x%} --><br />Your account must be approved before you can login. Once approved you can log in by using your email address and password by visiting our website or at the following URL:<br /><!-- {mid %x%} --><br />Your account has now been created and you can log in by using your email address and password by visiting our website or at the following URL:<br /><!-- {end %x%} -->';
$return= preg_replace($pattern_loop, "Content", $html, 1);

header('content-type: text/plain');
echo $return;
exit;

电流输出:

Content

预期输出,它只是替换自定义标签一次:

Content<br /><!-- {start %x%} --><br />Your account must be approved before you can login. Once approved you can log in by using your email address and password by visiting our website or at the following URL:<br /><!-- {mid %x%} --><br />Your account has now been created and you can log in by using your email address and password by visiting our website or at the following URL:<br /><!-- {end %x%} -->

1 个答案:

答案 0 :(得分:1)

在正则表达式结束时使用正向前看。
我刚刚删除了不必要的逃脱并简化了文本:

$pattern_loop = "/<!-- \{start %x%\} -->.*?<!-- \{mid %x%\} -->.*?<!-- \{end %x%\} -->(?=.*<!-- \{start %x%\} -->)/";
$html= '<!-- {start %x%} --><br />start 1<br /><!-- {mid %x%} --><br />mid 1<br /><!-- {end %x%} --><br /><!-- {start %x%} --><br />start 2<br /><!-- {mid %x%} --><br />mid 2<br /><!-- {end %x%} --><br /><!-- {start %x%} --><br />start 3<br /><!-- {mid %x%} --><br />mid 3<br /><!-- {end %x%} -->';
$return= preg_replace($pattern_loop, "Content", $html, 1);

echo $return;

<强>输出:

Content<br /><!-- {start %x%} --><br />start 2<br /><!-- {mid %x%} --><br />mid 2<br /><!-- {end %x%} --><br /><!-- {start %x%} --><br />start 3<br /><!-- {mid %x%} --><br />mid 3<br /><!-- {end %x%} -->