如何获得属性键不值使用PHP DOMDocument


How to get the attribute key not value using PHP DOMDocument

我有一个html字符串

$html_string = '<div style="font-family:comic sans ms,cursive;">
<div style="font-size:200%;">Some Text </div></div>';

我试过了

$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = $dom->getElementsByTagName('div');
for($i=0;$i<$divs->length;$i++) {
$attrib = $divs->item($i)->getAttribute("style");
echo $attrib;
echo '<br />';
}

它给出以下输出

font-family:comic sans ms,cursive
font-size:200%;
我需要

font-family
font-size

我怎样才能得到这些键而不是它们的值?

您可以使用regexp来做到这一点。像这样:

$style = 'font-family:comic sans ms,cursive;font-size:15em';
preg_match_all('/(?<names>[a-z'-]+):(?<params>[^;]+)[; ]*/', $style, $matches);
var_dump($matches['names']);
var_dump($matches['params']);
结果:

array
  0 => string 'font-family' (length=11)
  1 => string 'font-size' (length=9)
array
  0 => string 'comic sans ms,cursive' (length=21)
  1 => string '15em' (length=4)

这甚至可以使用多个CSS参数

使用CSS解析器!

所有explode和正则表达式的答案本质上都是错误的。您要分析的是CSS源代码。简单的文本操作永远不会正确地做到这一点。例如,background-image:url('http://my.server.com/page?a=1;b=2'); list-style-image:url('http://my2.server.com/page/a=1;b=2')是完全有效的,包含background-imagelist-style-image两个属性,大多数文本处理将失败,因为文本中间有分号或4个冒号(两者都会被错误的解决方案表示4个属性)。

一般来说,永远不要尝试在源代码中使用文本处理工具;不是CSS,不是HTML,也不是其他任何源代码。语言在设计上要比这复杂得多。这就是解析器要完成的,这也是为什么它们是BIG的原因——或者至少比strpos()更复杂…

在当前输出上使用explode,然后继续使用从explosion收到的第一个元素