Search code examples
phpstringpattern-matchingpreg-replacecontain

Check if string contains JS in PHP


I'm trying to create a function which would delete any potentional script tags, but not other tags like p, li, ol, span, h1, ...

This is what I have so far. I also wrote < and > as encoded chars "%3C" and "%3E" and as HTML name and number. Tried to do regex for first one as you see "^<(/)?script>$". But it's not working :D

function smartFilter($string) {
    $string = strtolower($string);
    if (strpos($string, "<script>") !== FALSE || strpos($string, "&#60;script&#62;") !== FALSE || strpos($string, "&lt;script&gt;") !== FALSE || strpos($string, "%3Cscript%3E") !== FALSE) {
        $unallowed = array("^<(\/)?script>$", "&lt;script&gt;", "&lt;/script&gt;", "%3Cscript%3E", "%3C/script%3E", "&#60;script&#62;", "&#60;script&#62;");
        return preg_replace($unallowed, "", $string);
    } else {
        return $string;
    }
}

Solution

  • Why not use strip_tags from php? Link here.