PHP preg_replace error

PHPpreg-replace

I have the following code:

protected function safePath($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);
    }

After I execute the function with a path, I get this error:

Warning: preg_replace() [function.preg-replace]: Compilation failed: unmatched parentheses at offset 3 in ……/myfile.php on line 534

where line 534 is this one marked with here:

protected function safePath($path) {
        $path = (string) $path;

        $path = preg_replace(
            array(
            '#[\n\r\t\0]*#im',
            '#/(\.){1,}/#i',
            '#(\.){2,}#i',
            '#(\.){2,}#i',
            '#\('.DIRECTORY_SEPARATOR.'){2,}#i'
            ),
            array(
            '',
            '',
            '',
            '/'
            ),   <---------------- THis is line 534
            $path
            )
        ;
        return rtrim($path,DIRECTORY_SEPARATOR);
    }

Any help with fixing this error ? Thank you.

Best Answer

in the final regex, you've escaped the opening parenthesis but not the closing one

'#\('.DIRECTORY_SEPARATOR.'){2,}#i'

should perhaps be...

'#\('.DIRECTORY_SEPARATOR.'\){2,}#i'
                           ^
                           |
                       missing slash

...or perhaps the slash shouldn't be there at all. Either way, its inconsistent.