PHP get specific styles from CSS

Active3 hr before
Viewed126 times

6 Answers


You can see that regex2 gives you more flexibility and options than others. I would also personally not recommend using parse_css function for it has the bug that would omit error in case your css has closing braces contain spaces. For example, if your CSS is:,If you want the included css-files, just search for <link rel="stylesheet" src="source">, otherwise you have to search for inline style-elements., I can get the CSS files without any problem. However the problem arises when it need to parse those fetched CSS. So I needed the regex solutions. Well thanks for the link, but I already had been there. But since I am less familiar with regex part, so I could not make proper use of that. – ashutosh Dec 19 '13 at 18:33 ,The above function uses primarily 2 regex and 1 function to parse CSS, making total 3 methods available to use. Every method has different output orders.

Thanks @Pete so much for the awesome link he shared. Following code snippets solved my problems. You can choose any of the regex/function.

private function parse_css($css)
    $css_array = array(); // master array to hold all values
    $element = explode('}', $css);
    foreach ($element as $element) {
        // get the name of the CSS element
        $a_name = explode('{', $element);
        $name = $a_name[0];
        // get all the key:value pair styles
        $a_styles = explode(';', $element);
        // remove element name from first property element
        $a_styles[0] = str_replace($name . '{', '', $a_styles[0]);
        // loop through each style and split apart the key from the value
        $count = count($a_styles);
        for ($a=0;$a<$count;$a++) {
            if ($a_styles[$a] != '') {
                $a_key_value = explode(':', $a_styles[$a]);
                // build the master css array
                $css_array[$name][$a_key_value[0]] = $a_key_value[1];
    return $css_array;

private function filter_css($css)
//$regex1 = '/([^{]+)\s*\{\s*([^}]+)\s*}/';  
//$regex2 = '/(?<selector>(?:(?:[^,{]+),?)*?)\{(?:(?<name>[^}:]+):?(?<value>[^};]+);?)*?\}/';
  $newcss = $this->parse_css($css);  //One way
//preg_match_all('regex1',$css,$newcss);  //another way
//preg_match_all('regex2',$css,$newcss);  //yet another way
  return $newcss;
load more v

Theoretically you could pull the user agent and attempt to do browser-specific CSS, but that is littered with problems and not recommended. ,Generate a random number, test the result, use it to set a random background image on your header.,You don’t want the client to re-download and re-parse all the CSS on *every* page…,Don’t forget that any php code is executed on the server before anything happens in the browser.

Instead of using the .css file extension, use .php

<link rel='stylesheet' type='text/css' href='css/style.php' />

At the top of your new style.php file set the Content-type back to CSS:

< ? php
header("Content-type: text/css; charset: UTF-8"); ?

Now you can set up variables for whatever you like:

< ? php
header("Content-type: text/css; charset: UTF-8");

$brandColor = "#990000";
$linkColor = "#555555";
$CDNURL = ""; ?

Below all that PHP stuff, you can just commence regular CSS writing, only you can intermix some PHP to spit out those variables.

#header {
   background: url("<?php echo $CDNURL; ?>/images/header-bg.png") no - repeat;
a {
   color: < ? php echo $linkColor; ? > ;


ul #main - nav li a {
   color: < ? php echo $linkColor; ? > ;

I did a totally static test page and it worked fine, then I tried this same technique within a WordPress site and no dice. The solution for me was to leave the file named style.css, and use .htaccess to parse it as PHP. Just make sure this code is in the .htaccess file (Apache servers only) at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.

<FilesMatch "^.*?style.*?$">
   SetHandler php5-script

Carlo DeAgazio wrote in to say this works for him in WordPress:

< ? php
$absolute_path = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
$wp_load = $absolute_path[0].

Do stuff like connect to WP database and grab user set values

header('Content-type: text/css');
header('Cache-control: must-revalidate'); ?
load more v

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used. ,However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be "navy": ,To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.,When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.



   <h1>This is a heading</h1>
   <p>This is a paragraph</p>
   <p>This is a paragraph</p>

In this case, you could set certain styles in your global CSS file as !important, thus overriding inline styles set directly on elements.,How is specificity calculated?,This is because the two declarations have equal selector type counts, but the html h1 selector is declared last.,Some examples with a higher specificity:

<div id="test">
load more v

Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML.[1] CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.[2] ,Using CSS, the same element can be coded using style properties instead of HTML presentational attributes: ,Cascading Style Sheets Cascading Style Sheets, PhD thesis, by Håkon Wium Lie – provides an authoritative historical reference of CSS,This further decouples the styling from the HTML document and makes it possible to restyle multiple documents by simply editing a shared external CSS file.

   <font color="red">Chapter 1.</font>
load more v

Inline CSS: Inline CSS contains the CSS property in the body section attached with element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute. Example:  ,Below is the HTML file that is making use of the created external style sheet  ,href attribute is used to specify the location of the external style sheet file.,Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

load more v

Other "styles-specific" queries related to "PHP get specific styles from CSS"