PEAR logo

HTML_CSS : The Definitive Guide

Searching for usage

Searching for selectors and properties

Searching for selectors and properties

This example give you ability to find if a selector is defined ($style1) and get all properties values. This example give you also ability to find in which selector a property is defined ($style2).

Suppose we have this stylesheet :

  1. #PB1 .cellI, #PB1 .cellA {
  2.   width: 10px;
  3.   height: 20px;
  4.   font-family: Courier, Verdana;
  5.   font-size: 8px;
  6.   float: left;
  7. }
  8.  
  9. #PB1 .progressBorder {
  10.   width: 122px;
  11.   height: 24px;
  12.   border-width: 1px;
  13.   border-style: solid;
  14.   border-color: navy;
  15.   background-color: #FFFFFF;
  16. }
  17.  
  18. #PB1 .progressPercentLabel {
  19.   width: 60px;
  20.   text-align: center;
  21.   background-color: transparent;
  22.   font-size: 14px;
  23.   font-family: Verdana, Tahoma, Arial;
  24.   font-weight: normal;
  25.   color: #000000;
  26. }
  27.  
  28. #PB1 .cellI {
  29.   background-color: #EEEECC;
  30. }
  31.  
  32. #PB1 .cellA {
  33.   background-color: #3874B4;
  34. }
  35.  
  36. body {
  37.     background-color: #E0E0E0;
  38.     color: navy;
  39.     font-family: Verdana, Arial;
  40. }

Example 11.5. Searching for selectors and properties

  1. <?php
  2. require_once 'HTML/CSS.php';
  3.  
  4. $css = new HTML_CSS();
  5. $css->parseFile('grep1.css');
  6.  
  7. // find all selectors beginning with #PB1
  8. $style1 = $css->grepStyle('/^#PB1/');
  9.  
  10. // find all selectors that set the color property
  11. $style2 = $css->grepStyle('/./', '/^color$/');
  12.  
  13. // dump a resume of selectors where to find your style request
  14. $kstyle1 = array_keys($style1);
  15. echo '<p>Selectors defined with "#PB1" are :<br />';
  16. echo implode(', ', $kstyle1);
  17. echo '</p>';
  18.  
  19. $kstyle2 = array_keys($style2);
  20. echo '<p>Selectors defined with property "color" are :<br />';
  21. echo implode(', ', $kstyle2);
  22. echo '</p>';
  23.  
  24. // dump all details of grep results
  25. for ($i = 1; $i < 3; $i++) {
  26.     $bg = (($i % 2) == 0) ? "#fff" : "#eee";
  27.     echo '<pre style="background-color:'.$bg.'">';
  28.     var_dump(${"style$i"});
  29.     echo '</pre>';
  30. }
  31. ?>
Line 5 :

Load the stylesheet definition. You may also load it by other methods such as HTML_CSS::parseString() or HTML_CSS::parseData().

Line 8 :

We set here the Perl pattern definition to find all selectors (single or group) beginning by #PB1.

Line 11 :

We set here the Perl pattern definition to find all selectors (single or group) that have a color property defined.

HTML_CSS : The Definitive Guide v 1.5.0 : January 15, 2008