mattegener mattegener - 10 days ago 6
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

<script>Text</script>

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:

<>TEXT</>

Answer

The answer is

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

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

Comments