Skip to content

Instantly share code, notes, and snippets.

@aalaap
Last active April 14, 2022 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalaap/0176bc6b2df799038f711cb6718dcddc to your computer and use it in GitHub Desktop.
Save aalaap/0176bc6b2df799038f711cb6718dcddc to your computer and use it in GitHub Desktop.
Strip Tags Only - An implemention of the PHP strip_tags function that only removes specified tags
<php
/**
* Strip Tags Only
*
* Just like strip_tags, but only removes the HTML tags specified and not all of
* them.
*
* @param String $text The text to strip the tags from.
* @param String|Array $allowedTags This can either be one tag (eg. 'p') or an
* array, (eg. ['p','br','h1']).
* @return String The text with the mentioned tags stripped.
* @author Aalaap Ghag <aalaap@gmail.com>
*/
function strip_tags_only($text, $allowedTags = [])
{
if (!is_array($allowedTags)) {
$allowedTags = [
$allowedTags
];
}
array_map(
function($allowedTag) use (&$text) {
$regEx = '#<' . $allowedTag . '.*?>(.*?)</' . $allowedTag . '>#is';
$text = preg_replace($regEx, '$1', $text);
},
$allowedTags
);
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment