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
I had issues with the regex solution, and the quick and dirty php explode solution fails with urls, so here is another non-regex solution that doesn't fail with urls:
$css = 'background-image:url(https://test.com/media.jpg);color:#777;font-size:16px;font-weight:bold;left:214px;position:relative;top:70px';
$attrs = explode(';', $css);
$parsed = [];
foreach($attrs as $attr) {
$first_colon_pos = strpos($attr, ':');
$key = substr($attr, 0, $first_colon_pos);
$value = substr($attr, $first_colon_pos + 1);
$parsed[$key] = $value;
}
Outputs:
Array
(
[background-image] => url(https://test.com/media.jpg)
[color] => #777
[font-size] => 16px
[font-weight] => bold
[left] => 214px
[position] => relative
[top] => 70px
)
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 )
Let try this it will work fine
str.replace(/(\w+[-]?\w+)(?=:)/gi,'\n[$1] => ').replace(/[:;]+/g,'')
Here's a quick-and-dirty script that does what you're asking:
<?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:
Array
(
[color] => #777
[font-size] => 16px
[font-weight] => bold
[left] => 214px
[position] => relative
[top] => 70px
)