Page 1 of 1

Matching number of characters

Posted: Wed Dec 05, 2007 3:20 am
by thatsme
How to check,

number-number-number-number-number-number

6 times numbers (any numbers (single, double, three digit etc)) followed by an hyphen, -

Code: Select all

if (preg_match ( "/^[0-9](-[0-9])*$/" , $str ) )
{
// match!
}
else
{
// doesn't match
}
it fails when i give 2, 3 digits.

Re: Matching number of characters

Posted: Wed Dec 05, 2007 4:25 am
by arjan.top
If you have [0-9] it will match only one character/digit, you have to write something like that [0-9]+, it will match numbers with one or more digits

And If you have number-number-number-number-number-number all the time you may want to use {5}, so it wont match
number-number-number-number-number-number-number

Somethin like that:

Code: Select all

"/^[0-9]+(-[0-9]+){5}$/"

Posted: Wed Dec 05, 2007 6:41 am
by thatsme
Thanks arjan.top,

i wanted the number any number of times and removed,

{5}
from

Code: Select all

"/^[0-9]+(-[0-9]+){5}$/"
and tested using below code,

Code: Select all

"/^[0-9]+(-[0-9]+)$/"
it fails even if i give, 6 numbers.

Posted: Wed Dec 05, 2007 7:29 am
by vigge89
In the second pattern you missed adding the plus sign after the repetitive subpattern;

Code: Select all

/^[0-9]+(-[0-9]+)+$/

Posted: Wed Dec 05, 2007 8:11 am
by superdezign
vigge89 wrote:In the second pattern you missed adding the plus sign after the repetitive subpattern;

Code: Select all

/^[0-9]+(-[0-9]+)+$/
I think you're after the asterisk, not the plus.

Posted: Wed Dec 05, 2007 8:27 am
by vigge89
superdezign wrote:
vigge89 wrote:In the second pattern you missed adding the plus sign after the repetitive subpattern;

Code: Select all

/^[0-9]+(-[0-9]+)+$/
I think you're after the asterisk, not the plus.
Ah yeah, my bad:

Code: Select all

/^[0-9]+(-[0-9]+)*$/

Posted: Tue Jan 08, 2008 1:15 am
by vapoorize
^ and $ are taken as string literals in preg if you don't add the m modifier, so it should be this if you mean to say the start and end of the line by those characters:

Code: Select all

/^[0-9]+(-[0-9]+)*$/m