PHP Remove JavaScript

前端 未结 7 1689
梦谈多话
梦谈多话 2020-12-03 07:13

I am trying to remove JavaScript from the HTML.

I can\'t get the regular expression to work with PHP; it\'s giving me an null array. Why?



        
相关标签:
7条回答
  • 2020-12-03 07:57
    function clean_jscode($script_str) {
        $script_str = htmlspecialchars_decode($script_str);
        $search_arr = array('<script', '</script>');
        $script_str = str_ireplace($search_arr, $search_arr, $script_str);
        $split_arr = explode('<script', $script_str);
        $remove_jscode_arr = array();
        foreach($split_arr as $key => $val) {
            $newarr = explode('</script>', $split_arr[$key]);
            $remove_jscode_arr[] = ($key == 0) ? $newarr[0] : $newarr[1];
        }
        return implode('', $remove_jscode_arr);
    }
    
    0 讨论(0)
  • 2020-12-03 08:00

    Here's an idea

    while (true) {
      if ($beginning = strpos($var,"<script")) {
        $stringLength = (strpos($var,"</script>") + strlen("</script>")) - $beginning;
        substr_replace($var, "", $beginning, $stringLength);
      } else {
        break
      }
    }
    
    0 讨论(0)
  • 2020-12-03 08:07

    this should do it:

    echo preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $var);
    

    /s is so that the dot . matches newlines too.

    Just a warning, you should not use this type of regexp to sanitize user input for a website. There is just too many ways to get around it. For sanitizing use something like the http://htmlpurifier.org/ library

    0 讨论(0)
  • 2020-12-03 08:07

    This might do more than you want, but depending on your situation you might want to look at strip_tags.

    0 讨论(0)
  • 2020-12-03 08:08

    In your case you could regard the string as a list of newline delimited strings and remove the lines containing the script tags(first & second to last) and you wouldn't even need regular expressions.

    Though if what you are trying to do is preventing XSS it might not be sufficient to only remove script tags.

    0 讨论(0)
  • 2020-12-03 08:14

    this was very usefull for me. try this code.

    while(($pos = stripos($content,"<script"))!==false){
        $end_pos = stripos($content,"</script>");
        $start = substr($content, 0, $pos);
        $end = substr($content, $end_pos+strlen("</script>"));
        $content = $start.$end;
    }
    $text = strip_tags($content);
    
    0 讨论(0)
提交回复
热议问题