Parse inline CSS values with Regex?

前端 未结 4 1859
Happy的楠姐
Happy的楠姐 2021-01-19 03:57

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

4条回答
  •  無奈伤痛
    2021-01-19 04:23

    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
    )

提交回复
热议问题