PHP - 将一串HTML属性拆分为索引数组

abe*_*ier 8 html php split

我有一个HTML属性的字符串:

$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';
Run Code Online (Sandbox Code Playgroud)

如何将该字符串转换为索引数组,如:

array(
  'id' => 'header',
  'class' => array('foo', 'bar'),
  'style' => array(
    'background-color' => '#fff',
    'color' => 'red'
  )
)
Run Code Online (Sandbox Code Playgroud)

所以我可以使用PHP array_merge_recursive函数来合并2组HTML属性.

谢谢

Ken*_*nan 20

使用SimpleXML:

<?php
$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';

$x = new SimpleXMLElement("<element $attribs />");

print_r($x);

?>
Run Code Online (Sandbox Code Playgroud)

这假设属性总是名称/值对...


Gum*_*mbo 8

您可以使用正则表达式来提取该信息:

$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';
$pattern = '/(\\w+)\s*=\\s*("[^"]*"|\'[^\']*\'|[^"\'\\s>]*)/';
preg_match_all($pattern, $attribs, $matches, PREG_SET_ORDER);
$attrs = array();
foreach ($matches as $match) {
    if (($match[2][0] == '"' || $match[2][0] == "'") && $match[2][0] == $match[2][strlen($match[2])-1]) {
        $match[2] = substr($match[2], 1, -1);
    }
    $name = strtolower($match[1]);
    $value = html_entity_decode($match[2]);
    switch ($name) {
    case 'class':
        $attrs[$name] = preg_split('/\s+/', trim($value));
        break;
    case 'style':
        // parse CSS property declarations
        break;
    default:
        $attrs[$name] = $value;
    }
}
var_dump($attrs);
Run Code Online (Sandbox Code Playgroud)

现在你只需要解析class(在空格中拆分)和属性声明的类style(稍微有些困难,因为它可以包含注释和URL ;).


Mar*_*iyo 6

简单的方法也可以是:

$atts_array = current((array) new SimpleXMLElement("<element $attribs />"));


tro*_*skn 5

您不能使用正则表达式来解析 html 属性。这是因为语法是上下文相关的。您可以使用正则表达式来标记输入,但您需要一个状态机来解析它。

如果性能不是什么大问题,最安全的方法可能是将属性包装在标签中,然后通过 html 解析器发送它。例如。:

function parse_attributes($input) {
  $dom = new DomDocument();
  $dom->loadHtml("<foo " . $input. "/>");
  $attributes = array();
  foreach ($dom->documentElement->attributes as $name => $attr) {
    $attributes[$name] = $node->value;
  }
  return $attributes;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过重用解析器或使用XmlReadersax parser来优化上述内容。