I recently wrote this function that, when supplied a string and an array of element types, will remove those element types from the string.
As you could imagine this is a very very simple function, but I wanted to get opinions on speed, functionality, and any other comments anyone can come up with that can improve this function.
<?
$str = <<<STRING
<b>Chocolate</b> is very <div class="vanilla">Chocolate</div>!
< b>England</b> is very <div class="skyscraper">City</div>!
<b>England</b> is my <div>city</div>
<b>England</b> is my <div>city</div>
<b>England</b> is my <span>city</span>
< b>Name</b>
<div class="myclass"></div>
<span>
STRING;
echo htmlentities(removeTags($str, array("b", "div", "span")));
function removeTags($str, $tags) {
$tagsString = "";
foreach($tags as $key => $v) {
$tagsString .= $key == count($tags)-1 ? $v : "{$v}|";
}
$patterns = array("/(<\s*\b({$tagsString})\b[^>]*>)/i", "/(<\/\s*\b({$tagsString})\b\s*>)/i");
$output = preg_replace($patterns, "", $str);
return $output;
}
?>
< b>Name</b>
,<div class="myclass"></div>
,<span>
(broken HTML, which browsers still parse), etc... You need an actual parser to mess with HTML: regexps won't do. \$\endgroup\$<span>
would also be removed properly. The use-case is meant to be a string that you want to remove elements from before they ever see the page \$\endgroup\$