Note that there are some explanatory texts on larger screens.

plurals
  1. POextract css classes and ID's from source with php
    text
    copied!<p>I thought this was going to be pretty simple, but I've been struggling with it now for a while. I know there are CSS parser classes out there that can acheive what I want to do... but I don't need 95% of the functionality they have, so they're not really feasible and would just be too heavy.</p> <p>All I need to be able to do is pull out any class and/or ID names used in a CSS file via regex. Here's the regex I <em>thought</em> would work, but hasn't.</p> <pre><code>[^a-z0-9][\w]*(?=\s) </code></pre> <p>When run against my sample:</p> <pre><code>.stuffclass { color:#fff; background:url('blah.jpg'); } .newclass{ color:#fff; background:url('blah.jpg'); } .oldclass { color:#fff; background:url('blah.jpg'); } #blah.newclass { color:#fff; background:url('blah.jpg'); } .oldclass#blah{ color:#fff; background:url('blah.jpg'); } .oldclass #blah { color:#fff; background:url('blah.jpg'); } .oldclass .newclass { text-shadow:1px 1px 0 #fff; color:#fff; background:url('blah.jpg'); } .oldclass:hover{ color:#fff; background:url('blah.jpg'); } .newclass:active { text-shadow:1px 1px 0 #000; } </code></pre> <p>It does match <em>most</em> of what I want, but it's also including the curly brackets and doesn't match the ID's. I need to match the ID's and Classes separately when conjoined. So basically <code>#blah.newclass</code> would be 2 separate matches: <code>#blah</code> AND <code>.newclass</code>.</p> <p>Any ideas?</p> <p>===================</p> <h1>FINAL SOLUTION</h1> <p>I wound up using 2 regex to first strip out everything between <code>{</code> and <code>}</code>, then simply matched the selectors based on the remaining input.</p> <p>Here's a full working example:</p> <pre><code>//Grab contents of css file $file = file_get_contents('css/style.css'); //Strip out everything between { and } $pattern_one = '/(?&lt;=\{)(.*?)(?=\})/s'; //Match any and all selectors (and pseudos) $pattern_two = '/[\.|#][\w]([:\w]+?)+/'; //Run the first regex pattern on the input $stripped = preg_replace($pattern_one, '', $file); //Variable to hold results $selectors = array(); //Run the second regex pattern on $stripped input $matches = preg_match_all($pattern_two, $stripped, $selectors); //Show the results print_r(array_unique($selectors[0])); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload