dongzhi9457
dongzhi9457
2018-08-02 12:56

使用Regex PHP从内联样式值中解析并创建关联数组[关闭]

已采纳

I have such an inline CSS like this

text-align:center; float:left;width:18%;

Expectation

Array
(
    [text-align] => center
    [float] => left
    [width] => 18%

)

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongwu3596 dongwu3596 3年前

    I found solution

    $r = array();
    preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", 'text-align:center; float:left;width:18%;', $arr, PREG_SET_ORDER);
    foreach ($arr as $v) {
      $r[$v[1]] = $v[2];
    }
    

    Demo https://regex101.com/r/qxanGV/1/

    Add explain usage https://regexr.com/3tcik

    点赞 评论 复制链接分享