Reputation: 5685
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
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:
So here is a non-regex approach.
if ( in_array(strlen($string),array(13,25)) && ctype_alnum($string) ) {
// good
} else {
// bad
}
Upvotes: 1
Reputation: 4320
This is a fast way:
preg_match('/^[a-zA-Z0-9]{13}([a-zA-Z0-9]{12})?$/', $string);
Upvotes: 4
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 25Example : http://regex101.com/r/bJ9vV5/1
Upvotes: 3