cakephp - Applying a CSS whitelist to HTML in PHP -
lets have following $string...
<span style='text-decoration:underline; display:none;'>some text</span>
i want allow style text-decoration
, want php function following...
$string = stripstyles($string, array("text-decoration"));
similar strip_tags
, using array instead. $string
be...
<span style='text-decoration:underline;'>some text</span>
i using cake, if can done sanitize better.
this tricky, should able domdocument
. should started, it's require serious tweaking.
// load html string $dom = new domdocument(); $dom->loadhtml($your_html_string); // <span> tags $spans = $dom->getelementsbytagname("span"); // loop on span tags foreach($spans $span) { // if have style attribute contains "text-decoration:" // attempt replace contents of style attribute text-decoration component. if ($style = $span->getattribute("style")) { if (preg_match('/text-decoration:([^;]*);/i', $style)) { $span->setattribute("style", preg_replace('/^(.*)text-decoration:([^;]*);(.*)$/i', "text-decoration:$2;", $style); } // otherwise, erase style attribute else $span->setattribute("style", ""); } } $output = $dom->savehtml;
it's maybe better attempt parse style attributes explode()
ing on ;
// replaces inner contents of foreach ($spans $span) above... // instead of preg_replace() $styles = explode(";", $style); $replaced_style = false; foreach ($styles $s) { if (preg_match('/text-decoration/', $s) { $span->setattribute("style", $s); $replaced_style = true; } // if text-decoration wasn't found, empty out style if (!$replaced_style) $span->setattribute("style", ""); }
Comments
Post a Comment