PHP中的PCRE只查找模式匹配的第一件事


PCRE in PHP only finding the first thing the pattern matches

我有以下模式使用它来匹配HTML标记:

~<([[:alpha:]]+) ([[:alpha:]]+=".*?")*>.*?</'1>~si

它可以很好地匹配任何标记,但它只会在整个字符串中搜索它遇到的第一个匹配。例如:

$text = <<<text
<p class="matches">some text, this will match</p>
<p>this won't match</p>
<p>this won't match either</p>
<p class="matches">this will match</p>
<p class="matches">this will match too</p>
<div>This won't match either but I want it to..</div>
text;
$pattern = '~<([[:alpha:]]+) ([[:alpha:]]+=".*?")*>.*?</'1>~si';
preg_match_all($pattern,$text,$matches);
var_dump($matches);

发布的代码将填充$matches,因为我想要它,但$matches[0][*]将只包含3段具有class="matches"属性(我测试了这种模式上的标签没有属性,它确实匹配那些正确的太)。exp不是我的堡垒……我做错了什么?

在元素和属性之间添加's?

~<([[:alpha:]]+)'s?([[:alpha:]]+=".*?")*>.*?</'1>~si

另外,你不应该在HTML中使用正则表达式