Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retrieve all colors from CSS file and store into array 1

Status
Not open for further replies.

Sleidia

Technical User
May 4, 2001
1,284
FR

Hi,

Using PHP, what would be the easiest way to retrieve all colors from a CSS file and store them all into an array?

Thanks! :)
 
Hi

Hmm... I think the situation is not so simple as I though first. If shorthand properties are used with named colors, it can be tricky :
Code:
* {
  background: url(image.png) aliceblue repeat-x center 33%;
}

Feherke.
 
Hi

Your question is an interesting one. I think I would do it like this :
Code:
$css=file_get_contents('example.css');

preg_match_all('/\b(?:color|background|border)[^:]*:(.*?);/',$css,$rule);

$value=array();
foreach ($rule[1] as $one) $value=array_merge($value,preg_split('/\s+/',$one));

$value=array_unique($value);

$value=array_filter($value,'check');

print_r($value);

function check($what)
{
  $keyword=array('none','inherit','repeat','repeat-x','repeat-y','no-repeat','scroll','fixed','top','bottom','left','right','center','thin','medium','thick','hidden','dotted','dashed','solid','double','groove','ridge','inset','outset','collapse');
  if (substr($what,0,1)=='#') return true;
  if (strtolower(substr($what,0,3))=='rgb') return false;
  if (is_numeric(substr($what,0,1))) return false;
  if (substr($what,0,1)=='.') return false;
  if (strtolower(substr($what,0,3))=='url') return false;
  if (in_array($what,$keyword)) return false;
  return true;
}

Feherke.
 
Thanks a lot feherke :)

Actually, I would only need to catch #------ style colors.
So, preg_match_all would be enough.

But I suck at PREGs :(

Thanks again!
 
Hi

Doh, that is too simple.
Code:
$css=file_get_contents('example.css');
                                             
preg_match_all('/#[[:xdigit:]]{3}(?:[[:xdigit:]]{3})?/',$css,$color);
                                                           
print_r($color[0]);

Feherke.
 
ahahaha ... thanks for showing me how much I suck at it ;)

And most of all, thanks for taking time to post the right PREG sequence.

Have a nice day :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top