PHP

Strip HTML Safely (whitelist tags)

admin by @admin ADMIN
Jun 20, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Strip nearly all HTML from a string but keep a small whitelist (e.g. links, line breaks, inline formatting). Wraps strip_tags with sensible defaults and a callback to also drop event-handler attributes.
PHP
Raw
<?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>
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.