Welcome to WebmasterWorld Guest from 54.167.175.107

Forum Moderators: coopster & jatar k

Age regular expression

I have the code, but it only kinda works.

   
11:26 pm on Aug 28, 2006 (gmt 0)

10+ Year Member



Ok, using this regualr expression to check to see if an age is between 1-105:

"([1-9][0-9]?)¦([10][1-6])"

Does not work, any suggestions?
--Nick

11:54 pm on Aug 28, 2006 (gmt 0)

10+ Year Member



"([1-9][0-9]?)(10[1-6])"

[10] = either 1 or 0 ; not "10"

12:18 am on Aug 29, 2006 (gmt 0)

5+ Year Member



You can do this with a simple condition:

$age = 50;
if ($age >= 1 && $age <= 105)
{
// Code
}
else
{
// Your age is invalid
}

12:34 am on Aug 29, 2006 (gmt 0)

10+ Year Member



That's fine, but it blows up with non integer characters.
--Nick
12:38 am on Aug 29, 2006 (gmt 0)

5+ Year Member



$age = <non-integer character> * 1;

It's a quick fix.

12:41 am on Aug 29, 2006 (gmt 0)

10+ Year Member



Cool-ness!
--Nick
6:54 pm on Aug 29, 2006 (gmt 0)

5+ Year Member



A simple way to check that the string only contains digits is as follows:

if (ctype_digit($age)) {
echo 'Age string contains only numbers.';
}

7:26 pm on Aug 29, 2006 (gmt 0)

5+ Year Member



if (!preg_match('#([0-9]+)#i', $str))
{
// Not Number
}
3:11 pm on Aug 30, 2006 (gmt 0)

5+ Year Member



Not that a regex is a good solution for this problem, but...

#([0-9]+)#i

would be better written as


/\d+/

\d is a synonym for [0-9], grouping (parentheses) is unnecessary, and reduces performance. Using Perl Regexp in PHP is generally un-optimal; better to use lower level string functions or integer casting and a regular conditional.

Also, just for readability, it might be better to use real type casting:


$age = (int) $nonIntChar;

instead of

$age = <non-integer character> * 1

But both those points are splitting hairs ;)

3:26 pm on Aug 30, 2006 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member




Using Perl Regexp in PHP is generally un-optimal; better to use lower level string functions or integer casting and a regular conditional.

I used to think this as well. As a matter of fact, most of the PHP function pages will even state as such. However, in my recent testing with PHP5 I have found PCRE to be faster. Perhaps it is the new engine or otherwise but I just wanted to share my experiences.

5:55 pm on Aug 30, 2006 (gmt 0)

WebmasterWorld Senior Member whoisgregg is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Or force an integer from any string with:

$age = intval($_POST['age']);
// OR
$age = (int) $_POST['age'];

Then do the <= && >= tests.

3:07 am on Aug 31, 2006 (gmt 0)

10+ Year Member



For future reference: Search Google for "regular expression tool". There are a lot of handy regex builders. A site called reWork has one I particularly like.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month