Regex pattern loop

Viewed 119

I ve got an string that have an specific format, which i want to check. To check if this format is correct i want to use regex. But the string format "12345x" can be endless. Example "12345t12345x".

My regex pattern for the format if it used only once is:

function useRegex($input) {
    $regex = '/^[0-9]+[a-zA-z]+$/i';
    return preg_match($regex, $input);
}
echo useRegex("12045t");

If the string is "12345t12345u" my code cant check it. So my question is if i can loop my regex pattern through the string?

1 Answers

You can use

preg_match('~^(?:\d{5}[A-Z])+$~iD', $input)

See the regex demo.

Details:

  • ^ - start of string
  • (?:\d{5}[A-Z])+ - one or more occurrences of:
    • \d{5} - five digits
    • [A-Z] - a single ASCII letter (case insensitive, due to i flag)
  • $ - end of string.

D flag stops matching if there is a trailing \n at the very end of string. If trailing newline is allowed, you may remove the flag.

Related