我试图在php中解析一串HTML标记属性。可能有3种情况:
attribute="value" //inside the quotes there can be everything also other escaped quotes
attribute //without the value
attribute=value //without quotes so there are only alphanumeric characters
有人可以帮我找到一个正则表达式,它可以在第一个匹配项中获取属性名称,在第二个匹配项中可以获得属性值(如果它存在)?
答案 0 :(得分:9)
Never ever use regular expressions for processing html,尤其是如果你正在编写一个库并且不知道你的输入会是什么样子。例如,请查看simplexml。
答案 1 :(得分:2)
尝试一下,看看它是否是你要从标签中提取的内容。
preg_match_all('/( \\w{1,}="\\w{1,}"| \\w{1,}=\\w{1,}| \\w{1,})/i',
$content,
$result,
PREG_PATTERN_ORDER);
$result = $result[0];
正则表达式提取每个属性,排除标记名称,并将结果放入数组中,这样您就可以遍历第一个和第二个属性。