2

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?

Laze Ho
  • 65
  • 7
  • Just use `preg_match_all('~\d+[A-Z]+~i', $input, $matches)` to extract all these matches. If you want to validate a string use `preg_match('~^(?:\d+[A-Z]+)+$~iD', $input)`. If you need to both extract and validate, it will be a bit more complex, but possible. – Wiktor Stribiżew Mar 07 '21 at 18:20
  • That dont work for my string format. The format ist everytime 5 random number from 0-9 then one random char, and this format can be loop or stack infinity. And i want to check this exact format with regex. But the length is not static and can be individuel so i need an regex pattern that can be infinit – Laze Ho Mar 07 '21 at 18:25
  • 1
    So, `preg_match('~^(?:\d{5}[A-Z])+$~iD', $input)`? – Wiktor Stribiżew Mar 07 '21 at 18:26

1 Answers1

1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563