phppreg-replaceeregereg-replace

error when changing ereg_replace to preg_replace


I am working on old sites and updating the deprecated php functions. I have the following code, which creates an error when I change the ereg to preg.

private function stripScriptTags($string) {
    $pattern = array("'\/\*.*\*\/'si", "'<\?.*?\?>'si", "'<%.*?%>'si", "'<script[^>]*?>.*?</script>'si");
    $replace = array("", "", "", "");
    return ereg_replace($pattern, $replace, $string);
}

This is the error I get:

Fatal error: Allowed memory size of 10000000 bytes exhausted (tried to allocate 6249373 bytes) in C:\Inetpub\qcppos.com\library\vSearch.php on line 403

Is there something else in that line of code that I need to be changing along with the ereg_replace?


Solution

  • So your regexes are as follows:

    "'\/\*.*\*\/'si"
    "'<\?.*?\?>'si"
    "'<%.*?%>'si"
    "'<script[^>]*?>.*?</script>'si"
    

    Taking those one at a time, you are first greedily stripping out multiline comments. This is almost certainly where your memory problem is coming from, you should ungreedify that quantifier.

    Next up, you are stipping out anything that looks like a PHP tag. This is done with a lazy quantifier, so I don't see any issue with it. Same goes for the ASP tag, and finally the script tag.

    Leaving aside potental XSS threats left out by your regex, the main issue seems to be coming from your first regex. Try "'\/\*.*?\*\/'si" instead.