Reputation: 3661
I have an html string
$html_string = '<div style="font-family:comic sans ms,cursive;">
<div style="font-size:200%;">Some Text </div></div>';
I have tried
$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 />';
}
it gives the following output
font-family:comic sans ms,cursive
font-size:200%;
I need
font-family
font-size
How can I get only these keys not the values they have?
Upvotes: 0
Views: 592
Reputation: 1923
Use a CSS parser!
All the answers with explode
and regular expressions are inherently wrong. It is CSS source-code you're trying to analyze. Simple text-manipulation will never do that correctly. E.g. 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')
is perfectly valid, contains the two properties background-image
and list-style-image
and most text-processing will fail either because there semicolons or 4 colons in the middle of the text (both would be mistaken by poor solutions to indicate 4 properties).
Generally, never try fiddling with text-manipulation tools in source code; not for CSS, nor HTML, nor any sourcecode else. Languages are by design more complicated than that. This is what parsers are meant to accomplish, and it is the same reason why they are BIG -- or at least more complicated than strpos()...
Upvotes: 1
Reputation: 3539
you can use regexps to do that. Something like this:
$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']);
result:
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)
this even works with with more than one css parameter
Upvotes: 1