Parse inline CSS values with Regex?

前端 未结 4 1827
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:18

    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
    )
    
    
    0 讨论(0)
  • 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
    )
    0 讨论(0)
  • 2021-01-19 04:34

    Let try this it will work fine

    str.replace(/(\w+[-]?\w+)(?=:)/gi,'\n[$1] => ').replace(/[:;]+/g,'')
    
    0 讨论(0)
  • 2021-01-19 04:35

    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
    )
    
    0 讨论(0)
提交回复
热议问题