CSS Declaration Grabber Regular Expression

2b-or-not-2bI use the same tools for development as Zach over at NoSheep. EditPlus is a sexy editor with all its FTP goodness, and packaged along with it are a number of syntax definitions for various languages as well as regular expressions for grabbing function declarations for those languages. Whats so cool about EditPlus and those regular expressions is: when you hit CTRL+F11 a handy window pops up with all the function definitions so you can click and jump to them quickly.

Sadly, EditPlus does not provide the the declaration regular expression for CSS by default…Most likely because CSS does not have any functions. Well, I live in CSS files while developing web UIs and as most people know, the CSS declarations can be hell to find. So, if you find yourself in the same place and don’t want to bother with an easy regular expression…here’s mine:

^[\t]*[a-zA-Z0-9\.# -_:@]+[\t]*\{.*[\t]*$

Comments

3 responses to “CSS Declaration Grabber Regular Expression”

  1. Sinan Özel Avatar
    Sinan Özel

    The following is the PHP code I used to create an array out of CSS declarations, including the regular expressions. I hope it is helpful.

    Sinan Özel


    while( preg_match( '/(?ims)([a-z0-9\s\.\:#_\-@]+)\{([^\}]*)\}/', $css, $arr ) ){
    $iLimit++;if( $iLimit > 10 ) break;
    $arrSelectors[trim($arr[1])] = trim($arr[2]);
    $css = str_replace( $arr[0], '', $css );
    }
    if( sizeof( $arrSelectors ) ){
    foreach( $arrSelectors as $selector=>$declaration ){
    unset( $arrSelectors[$selector] );
    while( preg_match( '/(?ims)([a-z0-9\s\.\:#_\-@]+)\:([^;]*)\;{0,1}/', $declaration, $arr ) ){
    $jLimit++;if( $jLimit > 10 ) break;
    $arrSelectors[$selector][trim($arr[1])] = trim( $arr[2] );
    $declaration = str_replace( $arr[0], '', $declaration );
    }
    }
    }

  2. Sinan Özel Avatar
    Sinan Özel

    The $iLimit and $jLimit lines are there for debugging, so you’ll want to remove them, or increase the 10 to 10 000 as a precaution.

  3. Zesposi Avatar
    Zesposi

    Thanks Matt, just what I was looking for.