mattegener mattegener - 1 year ago 117
PHP Question

Removing <script> tags using preg_replace

I'm filtering through a string (Pulled from a text file), and removing all and tags using preg_replace. For some reason, it is removing the actual text "script", but leaving the <> and . I've tried subbing in /< (to try and treat it as a literal), but that just generates errors. How do I get it to remove the brackets as well? The input is


Here's the code:

$file = file_get_contents($directory . "original-" . $name);
$file = htmlentities($file);
$file = preg_replace('<script>', '', $file);
$file = preg_replace('<\script>', '', $file);

And here is the output:


Answer Source

The answer is

$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);

But you might want to have a look at the strip_tags function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download