remove script tag from HTML content

remove script tag from HTML content

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Removing Script Tags Without Breaking Layouts

When sanitizing HTML, the default behavior of libraries like HTML Purifier is often too aggressive for specific use cases. By default, HTML Purifier strips out entire <script> blocks along with their contents and attributes. If your goal is strictly to neutralize executable code while preserving inline styles, classes, and other structural elements, you need to intervene in the filter definition itself.

HTML Purifier relies on a set of predefined filters that determine which tags are allowed and how they are processed. The core mechanism for removing script tags lies within the HTML.AllowedElements configuration, but simply setting this to an empty list or excluding scripts isn't enough if you want to keep the rest of the document intact. You must explicitly define a custom filter that permits all standard elements except <script>.

Here is how you configure HTML Purifier in PHP to achieve this:

$config = HTMLPurifier_Config::getInstance('default', array(
    'HTML.AllowedElements' => array_keys(HTMLPurifier_HTMLModule::$allowedModules), 
    'Cache.SerializerPath' => '/tmp/htpcache', // Ensure cache path exists and is writable
));

// Remove script specifically from the allowed list
$config->set('HTML.AllowedElements', array_diff($config->get('HTML.AllowedElements'), array('script')));

// However, a more robust approach is to define a custom module that excludes 'Script'
$config->set('HTML.SafeIframe', true); // Often needed for modern content
$config->set('URI.SafeIframeRegexp', '%^(https?://|www.)%');

// The most direct way to remove only script tags while keeping everything else:
$allowedElements = array_keys(HTMLPurifier_HTMLModule::$allowedModules);
if (isset($allowedElements['script'])) {
    unset($allowedElements['script']);
}
$config->set('HTML.AllowedElements', $allowedElements);

$purifier = new HTMLPurifier($config);
$safeHtml = $purifier->purify($dirtyHtml);

The critical detail here is understanding that HTML.AllowedElements acts as a whitelist. If you do not explicitly define which elements are allowed, the default behavior strips anything not on the list. By extracting the standard allowed modules and programmatically removing the script key, you ensure that no script tags pass through, while CSS styles defined via <style> tags or inline attributes on other elements remain untouched.

There is a nuance regarding how HTML Purifier handles these tags internally. Even if you remove the tag from the whitelist, the library might still attempt to process it based on its internal definition of what constitutes valid HTML. Therefore, ensuring that the Script module is not loaded or that the element is strictly excluded from the AllowedElements array is necessary. In some versions of HTML Purifier, you may also need to ensure that no custom modules are inadvertently re-introducing script capabilities.

Beyond configuration, there is a purely procedural way to achieve this if you prefer not to rely solely on the library's filtering engine for this specific task. You can use regular expressions or DOM parsing libraries like DOMDocument in PHP. While regex is tempting due to its brevity:

$cleanHtml = preg_replace('/<script\b.*?<\/script>/is', '', $dirtyHtml);

This approach has significant drawbacks. Regular expressions often struggle with malformed HTML, nested attributes, or script tags containing comments that span multiple lines. A regex solution might accidentally strip content inside <div> elements if not carefully escaped, or fail to handle cases where the closing tag is missing but implied by context. DOM parsing is safer because it respects the document tree structure, allowing you to traverse the nodes and remove only those with the script tagName while leaving siblings and parents intact.

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($dirtyHtml);

foreach ($doc->getElementsByTagName('script') as $script) {
    $script->parentNode->removeChild($script);
}

echo $doc->saveHTML();

This method is robust and handles edge cases better, though it requires managing the libxml error reporting to avoid fatal errors during parsing.

If you are building a larger application ecosystem where maintaining strict security boundaries is paramount without compromising on layout fidelity, HTML Purifier remains a strong candidate when configured correctly. For more advanced sanitization needs or if you require a managed solution that handles complex enterprise requirements, resources like https://laravelcompany.com can offer insights into integrating robust sanitization strategies within modern frameworks. However, for the specific task of stripping only script tags, precise configuration of the allowed elements list offers the best balance between security and content preservation.

Our network