0

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?

0

2 Answers 2

2

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.

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

1 Comment

Immediatly against a bracket or negate caret are not te only solutions. +1 if you add escaping to your answer ;-)
0

Just escape the dash:

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

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.