通过PHP将CSS转换为数组

luaexgnf  于 2023-01-29  发布在  PHP
关注(0)|答案(1)|浏览(144)

我有这个PHP函数(在另一个页面上找到的)将CSS数据转换为数组,它对大多数CSS都很有效,但当CSS有@media only screen and (max-width: 1800px)的例子时,CSS就显示不好了。
这是我正在使用的PHP函数:

function cssArray( $HTML_DATA_CSS ) {
    preg_match_all( '/(?ims)([a-z0-9\s\,\.\:#_\-@]+)\{([^\}]*)\}/', $HTML_DATA_CSS, $HTML_DATA_CSS_ARR);
    $HTML_DATA_CSS_OUTPUT    =    array();

    foreach ($HTML_DATA_CSS_ARR[0] as $i => $x) {
        $selector = trim($HTML_DATA_CSS_ARR[1][$i]);
        $rules = explode(';', trim($HTML_DATA_CSS_ARR[2][$i]));
        $HTML_DATA_CSS_OUTPUT[$selector] = array();

        foreach ($rules as $strRule) {
            if (!empty($strRule)) {
                $rule = explode(":", $strRule);
                $HTML_DATA_CSS_OUTPUT[$selector][][trim($rule[0])] = trim($rule[1]);
            }
        }
   }

   return $HTML_DATA_CSS_OUTPUT;
}

我怎样才能使这个函数也能在@media screen上工作?

vs91vp4v

vs91vp4v1#

<?php
function css_struct_to_array($string): array
{
  $string = preg_replace('/\s+/', ' ', $string);
  $string = preg_replace('/\s*:\s*/', ':', $string);
  $string = preg_replace('/\s*;\s*/', ';', $string);
  $string = preg_replace('/\s*{\s*/', '{', $string);
  $string = preg_replace('/\s*}\s*/', '}', $string);
  $explode = explode('}', $string);
  array_pop($explode);

  $output = [];
  foreach ($explode as $key)
  {
    $selector = explode('{', $key);
    $propertyes = [];
    $propertyes_explode = explode(';', $selector[1]);

    array_pop($propertyes_explode);

    foreach ($propertyes_explode as $key)
    {
      $property = explode(':', $key);

      $propertyes[$property[0]] = $property[1];
    }
    $output[$selector[0]] = $propertyes;
  }
  return $output;
}

https://github.com/Ariodevelop/C3S2Array
它多半管用!

相关问题