2

Regular expression in question:

$reg = '/[.]{1,}[\/\\]/';
if(preg_match($reg, $dir))...

I've tested this expression on http://regexpal.com and http://regex.larsolavtorvik.com/ it worked fine, but in my PHP script I'm getting this notification.

Message: preg_match() [function.preg-match]: Compilation failed: missing terminating ] for character class at offset 12

I've messed around with the number of '\', but it hasn't changed anything. Any suggestions on what might be going wrong?

I've tried to look for similar issues, but all I seem to run into is people who haven't added delimiters.

1

1 Answer 1

4

That's because \\ will be escaped by PHP to a single \, which will make preg_match evaluate your patterns as

/[.]{1,}[\/\]/

To have 2 backslashes in PHP string, you'll need to actually type 4:

$reg = '/[.]{1,}[\/\\\\]/';
preg_match($reg, "test");

Or use PHP's heredoc:

$reg = <<<REGEX
/[.]{1,}[\/\\\\]/
REGEX;
preg_match($reg, "test");

EDIT: seems like Heredoc also requires 4 backslashes. That's because of control characters like \n.

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

Comments

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.