正则表达式匹配HTML标记和属性

时间:2013-11-16 16:14:24

标签: php regex

我正在尝试匹配html标记名称及其属性。在下面的示例中,我尝试匹配divclassstyleid

$html='<div class="nav" style="float:left;" id="navigation">';
preg_match_all("/(([^<]\w+\s)|(\S+)=)/", $html, $match);

这将返回如下数组。

如您所见,正确的结果保存在Array [2]和Array [3]中。我想知道是否有可能将结果放在一个数组中,也许在Array [1]中?不知道怎么做。

Array
(
[0] => Array
    (
        [0] => div 
        [1] => class=
        [2] => style=
        [3] => id=
    )

[1] => Array
    (
        [0] => div 
        [1] => class=
        [2] => style=
        [3] => id=
    )

[2] => Array
    (
        [0] => div 
        [1] => 
        [2] => 
        [3] => 
    )

[3] => Array
    (
        [0] => 
        [1] => class
        [2] => style
        [3] => id
    )

)

1 个答案:

答案 0 :(得分:3)

您可以使用这个简单的正则表达式:

(?<=<)\w++|\b\w++(?==)

其中(?<=...)lookbehind(?=...)lookahead

示例:

preg_match_all('~(?<=<)\w++|\b\w++(?==)~', $html, $matches);
print_r($matches);

但是如果您使用多个捕获括号并且希望结果位于唯一数组中,则可以使用branch reset功能。示例(没有外观):

preg_match_all('~(?|<(\w++)|\b(\w++)=)~', $html, $matches);

(关于++,它是一个占有量词,通知正则表达式引擎它不需要回溯(除其他外,不记录回溯位置),这增加模式的性能,但这不是必需的(特别是对于小字符串)。您可以获得有关此功能的更多信息herehere