title: How to Remove unwanted Style attributes from HTML String Using PHP DOMDocument
body: <p>I have prepared a white list of allowed styles and I want to remove all the styles out of the white list from HTML String </p>
  
  <pre><code>$allowed_styles = array('font-size','color','font-family','text-align','margin-left');
  $html = 'xyz html';
  $html_string = '&lt;bdoy&gt;' . $html . '&lt;body&gt;';
  $dom = new DOMDocument();
  $dom-&gt;loadHTML($html_string);
  $elements = $dom-&gt;getElementsByTagName('body');
  foreach($elements as $element) {
  
  foreach($element-&gt;childNodes as $child) {
  
  if($child-&gt;hasAttribute('style')) {
  
  $style = strtolower(trim($child-&gt;getAttribute('style')));
  
  //match and get only the CSS Property name
  preg_match_all('/(?&lt;names&gt;[a-z\-]+):/', $style, $matches);
  
  for($i=0;$i&lt;sizeof($matches["names"]);$i++) {
  
    $style_property = $matches["names"][$i];
  
    // if the css-property is not in allowed styles array
    // then remove the whole style tag from this child
  
    if(!in_array($style_property,$allowed_styles)) {
  
     $child-&gt;removeAttribute('style');
     continue;
  
     }
  
  }
  
      }
    }
  }
  
  $dom-&gt;saveHTML();
  $html_output = $dom-&gt;getElementsByTagName('body');
  </code></pre>
  
  <p>I have tested so many html strings, it works fine every where. But When I tried to filter this html string</p>
  
  <pre><code>$html_string = ​'&lt;div style="font-style: italic; text-align: center; 
  background-color: red;"&gt;On The Contrary&lt;/div&gt;&lt;span 
  style="font-style: italic; background-color: rgb(244, 249, 255); 
  font-size: 32px;"&gt;&lt;b style="text-align: center; 
  background-color: rgb(255, 255, 255);"&gt;This is USA&lt;/b&gt;&lt;/span&gt;';
  </code></pre>
  
  <p>All other un allowed styles are removed from this string except this line</p>
  
  <pre><code>&lt;b style="text-align: center; background-color: rgb(255, 255, 255);"&gt;
  </code></pre>
  
  <p>Can Some one tell me any other efficient and robust way to remove the styles other than the whitelist</p>