1

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.

1 Answer 1

8

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 #.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to catch that particular error, i.e. can you "test" a pattern before using it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.