|
<?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 <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']) === '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>', []) === 'Foo <img /><b>bar</b>, <strong>baz</strong>, <b>qux</b>'); |
|
echo 'All assertions passed!'; |