PHP preg_replace() compilation failed: missing )

PHPpreg-replace

I have the following function to return a clean path for a script.

function cleanPath($path) {
        $path = (string) $path;
        $path = preg_replace(
            array(
            '#[\n\r\t\0]*#im',
            '#/(\.){1,}/#i',
            '#(\.){2,}#i',
            '#(\.){2,}#i',
            '#('.DIRECTORY_SEPARATOR.'){2,}#i'
            ),
            array(
            '',
            '',
            '',
            '/'
            ),
            $path
            )
        ;
        return rtrim($path,DIRECTORY_SEPARATOR);
    }

PHP gives the error:

Warning: preg_replace() [function.preg-replace]: Compilation
failed: missing ) at offset 7 in C:\wamp\www\extlogin\app\ni\inc\classes\cfiletree.php on line
18

Any ideas about what's wrong and how to fix it?

Thank you.

Best Answer

Most likely DIRECTORY_SEPARATOR is \ which means it'll escape the ) rather than match a backslash. You need to escape DIRECTORY_SEPARATOR so that it becomes \\ in the regex.

The safest way to escape strings placed in regular expressions is to use preg_quote:

preg_quote(DIRECTORY_SEPARATOR, '#');

The second argument, '#', is the separator you use for your regular expression, which in your case is #.