While using HTML Purifier, you may wish to specifically remove script tags without removing inline formatting or other elements. This can be accomplished through various methods.
Using Regular Expressions
Although not recommended for HTML parsing, a simple regular expression can achieve the task:
$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
Using DOMDocument
A more reliable and safe approach is to utilize the DOMDocument class, designed for HTML parsing:
$dom = new DOMDocument(); $dom->loadHTML($html); foreach ($dom->getElementsByTagName('script') as $item) { $item->parentNode->removeChild($item); } $html = $dom->saveHTML();
Additional Alternatives
Alternatively, consider using one of the following techniques:
Security Considerations
Remember that user input should be treated as potentially unsafe. Always sanitize and validate HTML content to prevent malicious code injection. Regular expressions should only be used on trusted content.
The above is the detailed content of How to Remove Script Tags from HTML Content: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!