首页 > 解决方案 > 如何使用正则表达式选择 CSS 文本?

问题描述

有人可以建议一个正则表达式来选择/分离css规则中的键值对并将它们转换为对象吗?

//css rules
animation-iteration-count: 1; animation-name: none; animation-play-state: running; 

进入这个:

{
'animation-iteration-count': 1, 'animation-name': none, 'animation-play-state': running 
}

和/或这个:

[
{key: 'animation-iteration-count', value: 1},
{key: 'animation-name', value:none },
{key: 'animation-play-state', value: running },
]

如果可能,首选 REGEX(或者如果没有,则使用 vanilla js)

标签: javascript

解决方案


不完全确定您要做什么,但我在 PHP 中编写了以下内容,以便为您提供一个良好的开端:

<?php
function cssJSON($fileName){
  $css = preg_replace('/(?<![a-z])\s+|\n+|\r+/i', '', file_get_contents($fileName));
  preg_match_all('/[^\/}]+{[^}]+}/', $css, $a); $m = $a[0]; $r = [];
  foreach($m as $c){
    $o = new StdClass; $q = explode('{', $c); $o->selectors = explode(',', $q[0]); $x = preg_replace('/;*}$/', '', $q[1]); $s = explode(';', $x); $o->style = [];
    foreach($s as $c){
      $z = explode(':', $c); $w = explode('-', $z[0]); $g = $z[1]; $b = new StdClass;
      if(isset($w[1])){
        $b->{$w[0].ucfirst($w[1])} = $g;
      }
      else{
        $b->{$w[0]} = $g;
      }
      $o->style[] = $b;
    }
    $r[] = $o;
  }
  return json_encode($r);
}
// usage
$json = cssJSON('css/external.css');
?>

它返回一个对象数组,其中包含一个selectors字符串数组和一个style对象数组。绕开!


推荐阅读