Alex
Alex

Reputation: 5685

Match a string with two different fixed lengths with preg_match

Is it possible to match a string of two different lengths with preg_match? And if yes, how?

I’m looking for something like this:

preg_match("/^[a-zA-Z0-9]{13|25}$/", $string);

As in, return true if $string las a length of exactly either 13 or 25 characters.

P.S.: I know that should be {13,25} — {min,max} —, but I’m not interested in matching within an interval.

Upvotes: 0

Views: 1063

Answers (3)

CrayonViolent
CrayonViolent

Reputation: 32532

I know your question was about doing it with regex, but it's generally best practice to avoid regex whenever possible. A few reasons why:

  • You should benchmark to be certain, but in most cases, built-in functions will out-perform regex.
  • Regex is not (thoroughly) understood by a lot of coders
  • Regex is usually less flexible as far as throwing new "business rules" / requirements into the mix. For example, what if you needed to add in a requirement to do something if the length is 13, and something different if it's 25? Or maybe do something if it's right chars but wrong length? You will not be able to code for these things with regex alone (The solution I present below doesn't address these "what ifs" either but the difference here is that you now have ability to separate the stuff as needed)

So here is a non-regex approach.

if ( in_array(strlen($string),array(13,25)) && ctype_alnum($string) ) {
  // good
} else {
  // bad
}

Upvotes: 1

Dávid Horváth
Dávid Horváth

Reputation: 4320

This is a fast way:

preg_match('/^[a-zA-Z0-9]{13}([a-zA-Z0-9]{12})?$/', $string);

Upvotes: 4

nu11p01n73R
nu11p01n73R

Reputation: 26667

Something like

preg_match("/^([a-zA-Z0-9]{13}|[a-zA-Z0-9]{25})$/", $string);
  • ([a-zA-Z0-9]{13}|[a-zA-Z0-9]{25} alternation matches either of length 13 or 25

Example : http://regex101.com/r/bJ9vV5/1

Upvotes: 3

Related Questions