0

I have css file that I am trying to manipulate using php. So if my css is like...

.something {
    display:none;
    background: blue;
}

.somethingElse {
    display:block;
}

I want to be able to get an array of the class names. So my array would look like...

['.something', '.somethingElse']

This is my attempt ($homepage is my css file)...

$homepage = file_get_contents("style.css");
$regex = '/[\s\S]\K[^{]*(?=})/m';
preg_match_all($regex, $homepage, $matches);

What I tried to do was find all strings that start with any character and end in open brace {. My regex is all wrong, what is the proper way?

buydadip
  • 8,890
  • 22
  • 79
  • 154
  • 1
    Try `'~^\h*\.([^\n{]*?)\s*{~m'`. To parse arbitrary CSS, use a CSS parser. See [Parse a CSS file with PHP](http://stackoverflow.com/questions/3618381/parse-a-css-file-with-php). – Wiktor Stribiżew Oct 05 '16 at 17:33
  • I think you'd be better served with a CSS parser written in PHP. – Matt S Oct 05 '16 at 17:34
  • What about multiple class names for one single CSS block? What if id names or other different selectors are between them? – revo Oct 05 '16 at 17:34

1 Answers1

1

This should work great:

\.([\w]+)\s*{

The class name is in group #1.

Example:

preg_match_all("/\.([\w]+)\s*{/", $homepage, $matches);
ByteBit
  • 333
  • 1
  • 9