用正则表达式在PHP中提取HTML属性 [英] Extract HTML attributes in PHP with regex

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

问题描述

我想从PHP的字符串获取HTML属性,但失败:

I want to get HTML attributes from string with PHP but fail with:

$string = '<ul id="value" name="Bob" custom-tag="customData">';
preg_filter("/(\w[-\w]*)=\"(.*?)\"/", '$1', $string ); // returns "<ul id name custom-tag"
preg_filter("/(\w[-\w]*)=\"(.*?)\"/", '$1', $string ); // returns "<ul value Bob customData"

我想返回的是:

array(
  'id' => 'value',
  'name' => 'Bob',
  'custom-tag' => 'customData'
);


推荐答案

HTML不是正规语言,无法正确解析与正则表达式。改用DOM解析器。以下是使用PHP内置的 DOMDocument 类的解决方案:

HTML is not a regular language and cannot be correctly parsed with a regex. Use a DOM parser instead. Here's a solution using PHP's built-in DOMDocument class:

$string = '<ul id="value" name="Bob" custom-tag="customData">';

$dom = new DOMDocument();
$dom->loadHTML($string);

$result = array();

$ul = $dom->getElementsByTagName('ul')->item(0);
if ($ul->hasAttributes()) {
    foreach ($ul->attributes as $attr) {
        $name = $attr->nodeName;
        $value = $attr->nodeValue;    
        $result[$name] = $value;
    }
}

print_r($result);

输出:

Array
(
    [id] => value
    [name] => Bob
    [custom-tag] => customData
)

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

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