php中html属性的正则表达式 [英] Regex for html attributes in php

查看:25
本文介绍了php中html属性的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 php 中的一串 HTML 标签属性.可能有 3 种情况:

I am trying to parse a string of HTML tag attributes in php. There can be 3 cases:

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

有人可以帮我找到一个正则表达式,它可以在第一个匹配属性名称,在第二个匹配属性值(如果存在)?

can someone help me to find a regex that can get in the first match the attribute name and in the second the attribute value (if it's present)?

推荐答案

试试这个,看看它是否是您想要从标签中提取的内容.

Give this a try and see if it is what you want to extract from the tags.

preg_match_all('/( \\w{1,}="\\w{1,}"| \\w{1,}=\\w{1,}| \\w{1,})/i', 
    $content, 
    $result, 
    PREG_PATTERN_ORDER);
$result = $result[0];

正则表达式提取每个属性,排除标签名称,并将结果放入一个数组中,这样您就可以遍历第一个和第二个属性.

The regex pulls each attribute, excludes the tag name, and puts the results in an array so you will be able to loop over the first and second attributes.

这篇关于php中html属性的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆