Skip to content

Instantly share code, notes, and snippets.

@mlaopane
Last active February 23, 2024 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlaopane/06ca477f7f2d204145f3ff54f976d892 to your computer and use it in GitHub Desktop.
Save mlaopane/06ca477f7f2d204145f3ff54f976d892 to your computer and use it in GitHub Desktop.
HTML cleaner to remove specific tags
<?php
/**
* Useful to remove tags (e.g <script>// some javascript code</script>)
*/
class HtmlCleaner
{
/**
* Remove tags from a string
* - opening tags
* - closing tags
* - self-closing tags
* - content inside the opening and closing tags if both exist
*
* @param string $html
* @param string[] $tags
* @return string
*/
public function cleanTags(string $html, array $tags): string
{
/** @var array[] Build the patterns */
$patterns = \array_reduce($tags, function ($stack, $tag) {
return array_merge($stack, [
"/<{$tag}.*{$tag}>/is",
"/<{$tag}\/*>/is",
"/<\/{$tag}>/is",
]);
}, []);
// Remove tags
$cleanedHtml = preg_replace($patterns, "", $html);
return $cleanedHtml;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment