简体   繁体   中英

PHP regex pattern modification needed

I'm sure this has been asked before and I did read through a lot of posts but nothing helped me. Since my regex knowledge is limited I thought I would ask for help.

I need to validate some user input (zip code format). Only certain characters are allowed: A , N , CC , ? , space ( ) and hyphen ( - ).

Sample Input Data

$input = "CC-XNNNNN", "ANNNNAAA", "AAAA NAA", "ANN ????"

Regex Pattern

$pattern = "(?:C{2})*|A*|N*|\?*|\-*|\ *"

PHP Code

if(preg_match('/' . $pattern . '/', $input))
{
 echo("pass<br>" . PHP_EOL);
}
else
{
 echo("fail<br>" . PHP_EOL);
}

I don't think I need to use anchors, because the allowed characters can be in any position. With the above code I get 'pass' but I should get 'fail' (X not allowed). I've looked this over so much I can't see the forest for the trees anymore.

Can anyone see what I've done wrong? OR is regex the wrong tool for this?

Could you please try following regex, written and tested with shown samples. Online demo of regex is: Regex online demo

^(?:[aA]|[nN]|[cC]{2}|\?|\s+|-)+$

Explanation: Adding detailed explanation for above.

^(?:       ##Starting a non capturing group from starting of value here.
[aA]       ##Checking if its either small a or capital A here.
|[nN]      ##OR if its N or n here.
|[cC]{2}   ##OR its c or C here with 2 occurrences.
|\?        ##Or its ? as a literal character.
|\s+       ##OR its one or more occurrences of spaces.
|-         ##OR its a dash
)+         ##Closing non capturing group and + will make sure only these characters follow
$          ##till end of the value.

Also I have matched characters with their small letter form also in case you don't need that we could change above to: ^(?:A|N|C{2}|\?|\s+|-)+$ then.

You could also use a character class instead of alternating between the single characters.

To also match the lowercase variant, you can use the /i flag

^(?:[AN? -]|CC)+$

The pattern matches:

  • ^ Start of string
  • (?: Non capture group
    • [AN? -] [AN? -] Match one of the listed characters
    • | Or
    • CC Match CC
  • )+ Close the group and repeat it 1+ times
  • $ End of string

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM