Search code examples
phpregexpreg-match

How do add an exception to preg_match


I have the following preg_match;

preg_match('=^\d?[a-z]{1,2}\d{1,4}[a-z]{1,3}$=i', $mystring);

This works great but I have some mystrings that have a /H or some other character. They also might end in -1, or -15 or other numbers.

Mystrings can look like this W0DLK, WA0DLK, W0DLK-1, W0DLK-20, W0DLK/H, W0DLK/M

How would I add to my existing preg_match to ignore anything after the '-' dash or the '/' slash? Substringing the value first would be difficult in my use.


Solution

  • You can use an optional capture group at the end of your expression so the hyphen/dash and characters are allowed.

    ^\d?[a-z]{1,2}\d{1,4}[a-z]{1,3}(?:[-/][a-z\d]+)?$
    

    This allowed a - or / and then letters and/or numbers. A stricter regex would be:

    ^\d?[a-z]{1,2}\d{1,4}[a-z]{1,3}(?:-\d+|/[a-z]+)?$
    

    This allows the string to end with a - and numbers, or a / and letters.

    1. https://regex101.com/r/6OxdZC/1/
    2. https://regex101.com/r/6OxdZC/2/