Last active
February 23, 2024 18:49
-
-
Save mlaopane/06ca477f7f2d204145f3ff54f976d892 to your computer and use it in GitHub Desktop.
HTML cleaner to remove specific tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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