Skip to content

Instantly share code, notes, and snippets.

@imliam
Created February 13, 2025 17:08
Show Gist options
  • Save imliam/69ae53fb2f35b328cea49ddd2fde49bd to your computer and use it in GitHub Desktop.
Save imliam/69ae53fb2f35b328cea49ddd2fde49bd to your computer and use it in GitHub Desktop.
<?php
/**
* Escape HTML tags in a string, except for the allowed tags.
*/
function escape_html_tags(string $string, array $allowedTags = []): string
{
$allowedTags = array_map('strtolower', $allowedTags);
return preg_replace_callback(
'/<[^>]*>/',
function ($matches) use ($allowedTags) {
$tag = strtolower($matches[0]);
$tag = substr($tag, 1, -1);
$tag = explode(' ', $tag, 2)[0];
$tag = trim(trim($tag, '/'));
if (in_array($tag, $allowedTags)) {
return $matches[0];
}
return htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8');
},
$string
) ?? $string;
}
assert(escape_html_tags('Foo <img /><b>bar</b>, <strong>baz</strong>, <b>qux</b>', ['strong', 'b', 'img']) === 'Foo <img /><b>bar</b>, <strong>baz</strong>, <b>qux</b>');
assert(escape_html_tags('Foo <img /><b>bar</b>, <strong>baz</strong>, <b>qux</b>', ['strong', 'b']) === 'Foo &lt;img /&gt;<b>bar</b>, <strong>baz</strong>, <b>qux</b>');
assert(escape_html_tags('Foo <img /><b>bar</b>, <strong>baz</strong>, <b>qux</b>', ['strong']) === 'Foo &lt;img /&gt;&lt;b&gt;bar&lt;/b&gt;, <strong>baz</strong>, &lt;b&gt;qux&lt;/b&gt;');
assert(escape_html_tags('Foo <img /><b>bar</b>, <strong>baz</strong>, <b>qux</b>', []) === 'Foo &lt;img /&gt;&lt;b&gt;bar&lt;/b&gt;, &lt;strong&gt;baz&lt;/strong&gt;, &lt;b&gt;qux&lt;/b&gt;');
echo 'All assertions passed!';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment