ablatt
ablatt

Reputation: 21

PHP preg_match expression not matching correct characters

I'm trying to catch any characters that are not letters, numbers, or .-_ (period, dash, underscore)

My code is

return !preg_match('/[^A-Za-z0-9.-_]/', $strToFilter);

My hope is that it will return false when it find an invalid character. As of now it allows ._ (period and underscore) but does not allow - (dash). It also does not detect characters like /, \, [, ], %, ^, etc as invalid characters.

What is wrong with my expression?

Upvotes: 0

Views: 478

Answers (2)

Goldentoa11
Goldentoa11

Reputation: 1760

In Regex character classes, you can't match a literal hyphen unless it is:

  1. immediately against either bracket,
  2. follows the negate caret (^), or
  3. is escaped using the backslash (\)

The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both [-x] and [x-] match an x or a hyphen. [^-x] and [^x-] match any character thas is not an x or a hyphen. This works in all flavors discussed in this tutorial. Hyphens at other positions in character classes where they can't form a range may be interpreted as literals or as errors. Regex flavors are quite inconsistent about this.

Source - See Metacharacters Inside Character Classes.

Upvotes: 2

Bohdan Yurov
Bohdan Yurov

Reputation: 360

Just escape the dash:

return !preg_match('/[^A-Za-z0-9.\-_]/', $strToFilter);

Upvotes: 0

Related Questions