Page 1 of 1

alpha-numeric fields

Posted: Wed Jun 13, 2007 8:08 am
by aceconcepts
Hi,

How can I check whether a field a certain contains letters and numbers? But in particular a certain amount of numbers.

i.e.

Field value = v41u3

How can I check if this field contains only 3 numbers?

Thanks.

Posted: Wed Jun 13, 2007 8:13 am
by feyd
A regular expression should suffice.

Posted: Wed Jun 13, 2007 8:37 am
by aceconcepts
hi,

Thanks for the rapid response.

I've found that I can use this in a regex: '(?<!\S)\d++(?!\S)'

This will match whole numbers in a string.

Now how would I count the instances of the numbers?

Thanks

Posted: Wed Jun 13, 2007 8:57 am
by volka
\d matches a single digit.
preg_match_all searches for all matches in a subject.
Just count all matches of a single digit.

Posted: Wed Jun 13, 2007 9:48 am
by aceconcepts
Could I be so bold as to ask for an illustration?

Posted: Wed Jun 13, 2007 9:52 am
by feyd
preg_match_all() returns the number of matches. The pattern to use is only \d, nothing more. It can't get more simple then that.

Posted: Wed Jun 13, 2007 10:13 am
by Ollie Saunders
Well, you have to use a delimiter either side of the regex (I use '~' and so the actual regex would be '~\d~')and use count() on the return value.

Posted: Wed Jun 13, 2007 8:41 pm
by feyd
It wouldn't need count(). ;)

Posted: Fri Jun 15, 2007 6:10 am
by aceconcepts
Using preg_match_all how can I count how many numbers are in a field?

Posted: Fri Jun 15, 2007 6:27 am
by stereofrog
Are you counting _digits_ or _numbers_ in a string? If first, just test the string against

Code: Select all

$re = '~^[a-z]*([0-9][a-z]*){1,3}$~iD';
if it matches, the string is alphanumeric and contains 1, 2 or 3 digits (change {1,3} to {3} to require exactly 3).

Posted: Fri Jun 15, 2007 8:53 am
by aceconcepts
What a wonderful piece of code! Works perfectly. Cheers.

Thanks a lot to all of u.