<?php
function safeStripHtml(string $html, array $allow = ['a','br','strong','em','code']): string {
$allowed = '<' . implode('><', $allow) . '>';
$clean = strip_tags($html, $allowed);
// Drop on* event handlers and javascript: URLs from any surviving tags.
$clean = preg_replace('/\s+on\w+\s*=\s*"[^"]*"/i', '', $clean);
$clean = preg_replace('/\s+on\w+\s*=\s*\'[^\']*\'/i', '', $clean);
$clean = preg_replace('/(href|src)\s*=\s*(["\']?)\s*javascript:[^"\'>\s]*/i', '$1=$2#', $clean);
return $clean;
}
echo safeStripHtml('<p onclick="alert(1)">Hi <a href="https://x.com">link</a><script>bad()</script></p>');
// Hi <a href="https://x.com">link</a>
Create a free account and build your private vault. Share publicly whenever you want.