Re: regular expressions ?

From: Date: Thu, 27 Jan 2005 16:28:37 +0000
Subject: Re: regular expressions ?
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-207502@lists.php.net to get a copy of this message
On Thu, 27 Jan 2005 16:56:05 +0100, Zouari Fourat <fourat@gmail.com> 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

« previous php.general (#207502) next »