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
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).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.