Reputation: 2822
preg_match('~^[a-zA-Z0-9!@#$%^*()-_+=.]+$~', $string)
This is the pattern I used in my code, What I wanted to do was telling users that they're only allowed to use these characters. But the problem is that it works for some characters and not for some others. For example it doesn't allow a string like "john&john" but it allows "test<>" even though I didn't enter '<' and '>' in the pattern!
Upvotes: 0
Views: 46
Reputation: 164
I always test my regexps with tools like that https://regex101.com/
You must escape some special characters in your regexp:
^[a-zA-Z0-9!@#\$%\^\*\(\)\-_\+=\.]+$
Upvotes: 1
Reputation: 785196
Problem is presence of an un-escaped hyphen in the middle of character class that is acting as range. Use this regex:
preg_match('~^[\w!@#$%^*()+=.-]+$~', $string)
Upvotes: 0
Reputation: 15351
Most of those characters in the pattern have special meaning for the regex engine and must be escaped with backslash:
^[a-zA-Z0-9\!\@\#\$\%\^\*\(\)\-\_\+\=\.]+$
https://regex101.com/r/kH7hD8/1
Upvotes: 2