Return CSS file classes using Regex and PHP

Asked

Viewed 43 times

1

I have the Following CSS:

.icon-a{
    background:black;
    color:white;
}    
.icon-b{
    backgroundwhite;
    color:black;
}    
.icon-c{
    background:blue;
    color:yellow;
}

I wanted a PHP script that could read the CSS file and return only the selector classes in an array:
Ex:

Array(
    0 => "icon-a",
    1 => "icon-b",
    2 => "icon-c"
 )

1 answer

1


You can use this regular expression, \.[\w-]+ a point following letter/number[a-za-Z0-9] a dash combining more than once, the modify m makes the combination work in multiline.

<?php

$css  ='.icon-a{
    background:black;
    color:white;
}    
.icon-b{
    backgroundwhite;
    color:black;
}    
.icon-c{
    background:blue;
    color:yellow;
}';


preg_match_all('#\.[\w-]+#m', $css, $m);

echo "<pre>";
print_r($m);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.