brasimon
brasimon

Reputation: 779

Escaping regular expressions inside square brackets

I'm trying to escape a parenthesis inside square brackets.

$pattern = "/^[a-zA-Z0-9 _-\(]{1,25}$/";
$str = "TEST (ok)";

if (preg_match($pattern, $str)) {
    echo "<br />OK";
} else {
    echo "<br />FAIL";
}

This give me the warning:

Warning: preg_match(): Compilation failed: range out of order in character class at offset 15 in /var/www/test.php on line 6
FAIL

Outside the square brackets the escaping works fine.

Any ideas?

Upvotes: 0

Views: 1149

Answers (2)

jtniehof
jtniehof

Reputation: 601

You need to escape the hyphen as well...as written, it will match from the underscore (ASCII 95) through the left paren (ASCII 40).

Upvotes: 2

CrayonViolent
CrayonViolent

Reputation: 32532

escape the hyphen or move it to the front or back of the char class list

Upvotes: 0

Related Questions