Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse inline CSS values with Regex?

Tags:

regex

css

php

I have such an 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. I'm about using "explode" function to parse the CSS into an array, something like :

Array(
"color" => "#777",
"font-size" => "16px",
"font-weight" => "bold",

and so on.

Can anybody suggest me a way to use regular expression to complete this task?

like image 320
Teiv Avatar asked Jan 21 '23 22:01

Teiv


1 Answers

Another way, using a regex:

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

$results = array();
preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $css, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
  $results[$match[1]] = $match[2];
}

print_r($results);

Outputs:

Array
(
    [color] => #777
    [font-size] => 16px
    [font-weight] => bold
    [left] => 214px
    [position] => relative
    [top] => 70px
)
like image 139
gnarf Avatar answered Jan 30 '23 18:01

gnarf