これはかなり簡単になると思いましたが、しばらく苦労していました。私がやりたいことを達成できるCSSパーサークラスがあることは知っています...しかし、それらの機能の95%は必要ないので、実際には実現可能ではなく、重すぎるだけです。
私ができる必要があるのは、正規表現を介してCSSファイルで使用されているクラス名やID名を引き出すことだけです。これが私がうまくいくと思った正規表現ですが、うまくいきませんでした。
[^a-z0-9][\w]*(?=\s)
私のサンプルに対して実行した場合:
.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;
}
それは私が望むもののほとんどと一致しますが、中括弧も含まれており、IDとは一致しません。結合する場合、IDとクラスを別々に一致させる必要があります。したがって、基本的に#blah.newclass
は2つの別々の一致になります:#blah
AND .newclass
。
何か案は?
===================
最終的解決
私は2つの正規表現を使用して、最初に{
との間のすべてを取り除き}
、次に残りの入力に基づいてセレクターを単純に一致させました。
完全に機能する例を次に示します。
//Grab contents of css file
$file = file_get_contents('css/style.css');
//Strip out everything between { and }
$pattern_one = '/(?<=\{)(.*?)(?=\})/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]));