title: How to I remove *some* inline CSS, but not all, using PHP?
body: <p>A PHP regex / PHP DOM / PHP XPath question.</p>
  
  <p>Given the following HTML with inline CSS:</p>
  
  <pre><code>&lt;p style='text-indent: 22px; font-weight: bold; line-height: 1em; color: #FFF'&gt;
  </code></pre>
  
  <p>How do I remove the 'line-height' and 'color' CSS properties, and leave text-indent and font-weight untouched, so the resultant HTML is:</p>
  
  <pre><code>&lt;p style='text-indent: 22px; font-weight: bold;'&gt;
  </code></pre>
  
  <p>The HTML file could be potentially hundreds of lines, with various nesting of tags and other attributes applied to any tag.</p>
  
  <p>Note that the 'style' attribute may be applied to other tags than <code>&lt;p&gt;</code></p>
  
  <p>I am aware there are approaches using both PHP DOM and regex - my current thinking was using something along these lines:</p>
  
  <pre><code>$elements = $xPath-&gt;query('//*[@style="color"]');
  foreach ($elements as $element) {   
    //remove style='color'
  }
  </code></pre>
  
  <p>Many thanks</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here's my solution:</p>
  
  <p><a href="https://github.com/sabberworm/PHP-CSS-Parser" rel="nofollow">https://github.com/sabberworm/PHP-CSS-Parser</a></p>
  
  <p>To create:</p>
  
  <pre><code>$dom = new DOMDocument;
  @$dom-&gt;loadHTML('&lt;?xml encoding="UTF-8"&gt;' . $html);
  $xPath = new DOMXPath($dom);
  $elements = $xPath-&gt;query('//p|//span');
  foreach($elements as $element){
      $oParser = new CSSParser("p{" . $element-&gt;getAttribute('style') . "}");
      $oCss = $oParser-&gt;parse();
      foreach($oCss-&gt;getAllRuleSets() as $oRuleSet) {
          $oRuleSet-&gt;removeRule('line-');
          $oRuleSet-&gt;removeRule('margin-');
          $oRuleSet-&gt;removeRule('font-');
      }
      $css = $oCss-&gt;__toString();
      $css = substr_replace($css, '', 0, 3);
      $css = substr_replace($css, '', -1, 1);
      $element-&gt;setAttribute('style', $css);
  }
  $src = $dom-&gt;saveHTML();
  </code></pre>