Jump to content

Removing javascript from string


Guest

Recommended Posts

This doesnt seem complicated but it is becoming a pain. I have a function that does a great job removing javascript here it is.

 

function strip_script($string) {
    // Prevent inline scripting
    $string = preg_replace("/<script[^>]*>.*<*script[^>]*>/i", "", $string);
    // Prevent linking to source files
    $string = preg_replace("/<script[^>]*>/i", "", $string);

    //styles
    $string = preg_replace("/<style[^>]*>.*<*style[^>]*>/i", "", $string);
    // Prevent linking to source files
    $string = preg_replace("/<style[^>]*>/i", "", $string);
    return $string;
}

 

Now the problem is when there is multiple lines like this

 

<script></script>  then some content <script></script>

 

Then all the content in the middle is removed. I want to keep 'then some content'

 

I have searched and cannot find out what is causing this or a solution so can someone please help me and save me from madness.

Link to comment
https://forums.phpfreaks.com/topic/109835-removing-javascript-from-string/
Share on other sites

Might wanna be careful with this script...

 

<?php

function strip_script($string) {
    // Prevent inline scripting
    //$string = preg_replace("/<script[^>]*>.*<*script[^>]*>/i", "", $string);
$string = preg_replace("/<script[^>]*>.*?< *script[^>]*>/i", "", $string);
    // Prevent linking to source files
    $string = preg_replace("/<script[^>]*>/i", "", $string);

    //styles
    $string = preg_replace("/<style[^>]*>.*<*style[^>]*>/i", "", $string);
    // Prevent linking to source files
    $string = preg_replace("/<style[^>]*>/i", "", $string);
    return $string;
}

$cnt = <<<H
<scr<script>ipt language="javascript">alert('lol')</script>
H;

echo strip_script($cnt);


/*
Output:
<script language="javascript">alert('lol')</script>
*/

 

 

You should either do a loop that continues to replace the stuff for as long as it finds it, or you should simply escape user input when displaying it (htmlentities).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.