views:

86

answers:

3

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.

+1  A: 

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.

Paul Dixon
A: 

Mighty odd, I can only get that error if both parethesees are escaped:

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

Maybe because you are not escaping the DIRECTORY_SEPARATOR ?

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

It's because of this part right here:

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

I'm guessing you're on a linux system. On Windows, the DIRECTORY_SEPARATOR is a backslash, which matches with the initial backslash you have on that line.

On linux, the DIRECTORY_SEPARATOR is a forward slash, and therefore this string has an escaped left bracket at the start, and no matching bracket at the end.

You can reproduce the error on either type of OS by simply replacing the DIRECTORY_SEPARATOR on that line with either a / or a \. You'll see the result right away.

zombat
Hmm... that was my answer too, better wording here though.
SeanJA