PHP Script to Parse inline CSS



Following script shows us how to parse inline CSS like this

color:#777;font-size:16px;font-weight:bold;left:214px;position:relative;top:70px

The CSS may end with a semicolon ";" or not. It also can contain extra space between its values.


<?php

$css 
"color:#777;font-size:16px;font-weight:bold;left:214px;position:relative;top:   70px";

$attrs explode(";"$css);

foreach (
$attrs as $attr) {
   if (
strlen(trim($attr)) > 0) {
      
$kv explode(":"trim($attr));
      
$parsed[trim($kv[0])] = trim($kv[1]);
   }
}
?>

And the output of print_r($parsed) is:

<?php
Array
(
   [
color] => #777
   
[font-size] => 16px
   
[font-weight] => bold
   
[left] => 214px
   
[position] => relative
   
[top] => 70px
)

?>