1

I have this PHP function ( found it on a different page ) to convert CSS data to array its working good for most of CSS but when the CSS has example @media only screen and (max-width: 1800px) on CSS is not showing well.

This is the PHP Function I'm using:

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;
}

How I can make the function to work with @media screen too?

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
Matei Zoc
  • 3,739
  • 3
  • 16
  • 18
  • 2
    Possible Duplicate of : https://stackoverflow.com/a/19307693/1140136 – Ashraf Jul 22 '18 at 03:56
  • I find what i was need on that page, thank you! – Matei Zoc Jul 22 '18 at 05:44
  • Possible duplicate of [Parse a CSS file with PHP](https://stackoverflow.com/questions/3618381/parse-a-css-file-with-php) – Sumithran Jul 22 '18 at 05:52
  • I like this function. It was perfect for basic CSS with no media query. But I replaced `$HTML_DATA_CSS_OUTPUT[$selector][][trim($rule[0])]` with `$HTML_DATA_CSS_OUTPUT[$selector][trim($rule[0])]` as there's no need to nest extra arrays. – Onimusha Jul 28 '22 at 01:13

1 Answers1

0
<?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

it most work!