Files
qztool/backend/app/Support/HtmlSanitizer.php
T

23 lines
722 B
PHP
Raw Normal View History

<?php
namespace App\Support;
class HtmlSanitizer
{
public static function clean(?string $html): string
{
$html = strip_tags((string) $html, '<p><br><strong><em><ul><ol><li><a><h2><h3><code>');
$html = preg_replace('/\son\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html) ?? '';
$html = preg_replace_callback('/<a\b([^>]*)>/i', function (array $matches) {
$attrs = $matches[1];
if (! preg_match('/href\s*=\s*("|\')(https?:\/\/[^"\']+)\1/i', $attrs, $href)) {
return '<a>';
}
return '<a href="'.htmlspecialchars($href[2], ENT_QUOTES).'" rel="noopener noreferrer">';
}, $html) ?? '';
return $html;
}
}