【问题标题】:Extract HTML attributes in PHP with regex [duplicate]使用正则表达式在 PHP 中提取 HTML 属性 [重复]
【发布时间】:2014-04-29 23:57:50
【问题描述】:

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

$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'
);

【问题讨论】:

  • 为什么我赞成这个问题,因为大多数答案都是基于 DOM,但我想通过常规经验了解

标签: php html regex


【解决方案1】:

Don't use regexes for parsing HTML

$string = '<ul id="value" name="Bob" custom-tag="customData">';
$dom = new DOMDocument();
@$dom->loadHTML($string);
$ul = $dom->getElementsByTagName('ul')->item(0);
echo $ul->getAttribute("id");
echo $ul->getAttribute("name");
echo $ul->getAttribute("custom-tag");

【讨论】:

  • 如果有更多的属性呢?另外,你为什么在这里使用错误抑制?
  • 这只是演示如何获取这些值。如果他们想遍历他们的所有属性,不难更进一步。错误抑制器只是为了防止它们在无效的 HTML 中。它将隐藏 PHP 将抛出的警告。
  • 同意第一部分。但是最好只使用libxml_use_internal_errors() 来存储错误状态的当前值,清除错误缓冲区并恢复旧的错误状态。 @ 的使用很糟糕,IMO。
【解决方案2】:

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

$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
)

【讨论】:

  • 他正在使用 REGEX 询问具体问题
  • @Emad:是的,但是正则表达式不是解析 HTML 的合适工具。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2015-02-26
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多