Search code examples
phpregexpreg-match

preg_match and regex - allow or exclude characters


I have problem with allowing specified characters in preg_match. I've tried making following pattern: /^[A-Za-z0-9 !@#$%&()-_\[\]:;\"'|,.\?\/]/ Right now it allows everything, even * which is not there.

I know that there's this rule that before regex specified characters I have to put "\" before character. Correct me if I'm wrong.

Can someone explain me how does this work?

I want to allow this chars: A-Z a-z 0-9 !@#$%&()-_[]:;"'|,.?/ (and of course spaces)

And exclude this: ~`^*+={}<>\


Solution

  • An unescaped hyphen needs to be at first or last position in a character class or it needs to be escaped. Otherwise it is considered a range. So use:

    /^[A-Za-z0-9 !@#$%&()_\[\]:;\"'|,.\?\/-]/
    

    In your regex /^[A-Za-z0-9 !@#$%&()-_\[\]:;\"'|,.\?\/]/ where - is in the middle of and ) (ASCII: 41) and _ (ASCII: 95), hence matching all the characters in this range.

    Also you need to use anchors to match entire input:

    /^[A-Za-z0-9 !@#$%&()_\[\]:;\"'|,.\?\/-]+$/