0

Possible Duplicate:
Parse a CSS file with PHP

I want to be able to search through a css file find the class or id and bring back its style.

IE.. css file layout

body {
margin:0;
padding:0; 
}
span {
margin:0;
padding:0; 
} #input { font:12px arial; }
a { color:#0000FF;
text-decoration:none; 
}
.logout a:hover { text-decoration:underline; }

and i want to find say the id " #input " in the file and it to bring back the style so.

font:12px arial;

or #input{ font:12px arial; }

and ovioulsly if there is more bring that back to but to keep this small like.

i tried my self but no luck as im not so good in regular expressions.

if(file_exists("css/style.css") && filesize("css/style.css") > 0){
$filesize = filesize("css/style.css");
$handle = fopen("css/style.css", "r");
$contents = fread($handle, $filesize);
fclose($handle);
}
preg_match('@^(?:#input{)?([^}]+)@i', $contents, $matches);
echo "style: {$matches[0]} <br>";
print_r($matches2);

please help.

Community
  • 1
  • 1
MasterT
  • 623
  • 1
  • 9
  • 23

1 Answers1

1

Your specific regex fails for a couple of reasons:

 @^(?:#input{)?([^}]+)@i
  • The ^ marker means start of subject. Since your #input { CSS selector is not at the start of the regex, this would always fail.

  • Secondly you are marking it optional with (...)?. So the regex will ignore looking for #input anyway.

  • Then you also don't have the { escaped.

  • And your actual CSS contains a space between #input and { which your regex does not account for.

More correct would be:

@(?:#input\s*\{)([^}]+)@i

See also Open source RegexBuddy alternatives and Online regex testing for some helpful tools, or RegExp.info for a nicer tutorial.

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291
  • Thank you mario i quest that whats was happening but was not sure on how to get it to work. but thanks it works a treat – MasterT Nov 14 '12 at 00:15
  • ok so how would i then go about finding say height and changing the value of the height so if the code is height: 20px; i want to change the 20px into 10px say so it would be height: 10px; but teh value will be different based on the search and the change value will be different also based on some other stuff. – MasterT Nov 14 '12 at 00:35
  • Use `preg_replace_callback` for finding the `{...}` block, then a second regex `height:\s*\d+px` with just `preg_replace` for the width and height. – mario Nov 14 '12 at 11:16