【发布时间】:2014-02-12 13:28:38
【问题描述】:
我需要在 HTML 的一部分上执行递归 str_replace(递归我的意思是首先是内部节点),所以我写道:
$str = //get HTML;
$pttOpen = '(\w+) *([^<]{1,100}?)';
$pttClose = '\w+';
$pttHtml = '(?:(?!(?:<x-)).+)';
while (preg_match("%<x-(?:$pttOpen)>($pttHtml)*</x-($pttClose)>%m", $str, $match)) {
list($outerHtml, $open, $attributes, $innerHtml, $close) = $match;
$newHtml = //some work....
str_replace($outerHtml, $newHtml, $str);
}
这个想法是首先替换非嵌套的 x-tags。 但它只有在innerHtml 在开始标签的同一行时才有效(所以我想我误解了 /m 修饰符的作用)。我不想使用 DOM 库,因为我只需要简单的字符串替换。有什么帮助吗?
【问题讨论】:
-
您能否在您的问题中添加一个具有预期输出的示例?
-
@CasimiretHippolyte 几乎同时出现同样的问题! :)
-
修饰符 m 将锚点
^和$(您不使用)的含义更改为“行首”和“行尾”。 -
您使用
$newHTML所做的“工作”也很有用。 -
对 HTML 代码的操作 -> 始终使用 DOM 解析器,而不是正则表达式。 (xpath, domdocument, simplexml, sax..)