Simple RegEx

I wondered if anyone can tell me a PHP regular expression to use which will return true if a string does not contain only numbers or is not 15-25 digits in length. Sorry if that’s a bit unclear.

I’m currently using:

!preg_match('/[0-9 ]{15, 25}/', $myString);

This works fine but I’m curious how to do it without putting NOT in front.

Best regards,

Dan

The Regex modifier for “NOT” is ^, so [^0-9] would select everything that isn’t a number.

Thanks Kokos. That I worked out. Do you know if there’s a way to incorporate the number of characters into it in the same statement?

your current regex won’t work because you aren’t anchoring it - i.e. it will accept strings like:

abcdefg1234567890123456

It gets a little ugly trying to meet your criteria, but something like this should work:

preg_match('#(\\D|(^.{,14}$)|(^.{26}))#', $myString);

Sounds an awful lot like a homework question. But look at Escape Characters
and ask yourself “How do I check for the existance of a 0-14 digit string. Now, how do i check for anything that ISNT a digit? Now, how do I check for a 26+ digit string”

PS: Your line doesnt work. (Inside of a 30 digit string is a 25 digit string…)

For the record, it might be easier to do it outside of preg.


if(strlen($myString) <= 14 || strlen($myString) >= 26 || preg_match('#[^0-9]#',$myString)) {
 echo "Bad String";
} else {
 echo "Good String";
}

Thanks StarLion, that appears to be the neatest solution so I’ll use that.

Thanks to everyone for your quick answers.