Re: regular expressions ?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 27 Jan 2005 16:56:05 +0100, Zouari Fourat <fourat@xxxxxxxxx> wrote:
> > this is working fine :
> > if (eregi("^-?([1-3])+$",$x)
> >  echo "x is 1 or 2 or 3";
> 
> i forgot to say that doesnt work with 1-20 :(
> how to do it ?

You're far better off doing it arithmetically as someone already said,
however  if you absolutely *have* to use a regexp then this is how you
go about it:

You need to match these possible variations:
1. the number '20'
2. the number '1' followed by any digit between 0 and 9.
3. any digit between 1 and 9.

the pattern for the first one is easy. it's just a fixed string: 20
the pattern for the second is only slightly harder: 1[0-9]
the pattern for the third is: [1-9]

You want to match any of them, so you join them together with an
alternation operator, the '|' symbol to get: 20|1[0-9]|[1-9]

This will match any string that contains the numbers 1-20, such as
'200'. To make sure it only matches exactly the numbers you're
interested in, you have to "anchor" the start and finish ending up
with this:

if (preg_match('/^(20|1[0-9]|1-9])$/', $candidate)) {
   // $candidate is a decimal integer between 1 and 20 inclusive with
no leading zeros.
}

 -robin

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux