Page 1 of 1

Regex, numerals and using variables for bounds

Posted: Tue Jun 08, 2010 10:42 am
by phpBever
The following code works nicely:

Code: Select all

function validateNames($str2val, $minVal, $maxVal)
{
  $pattern = '/^[a-zA-Z-,\'.& ]{'.$minVal.',' .$maxVal.'}$/';
  if(preg_match($pattern, $str2val)) return True;
  else return False;
}

$str2val = $_POST['theName'];
$minVal = 1;
$maxVal = 5;
$check = validateNames($str2val, $minVal, $maxVal);
if ($check === True) echo "Validated";
else echo "Not valid input";
However I'm having real trouble with this parallel function:

Code: Select all

function validateNumbers($str2val, $minVal, $maxVal)
{
  $pattern = '/^[0-9]{'.$minVal.', '.$maxVal.'}$/';
  if(preg_match($pattern, $str2val)) return True;
  else return False;
}

$minVal = 1;
$maxVal = 5;
$str2val = (int)$_POST['theName'];
$check = validateNumbers($str2val,$minVal, $maxVal);
if ($check === True) echo "Validated";
else echo "Not valid input";
If I go into the regexp and use '1' and '5' rather than $minVal and $maxVal, it works. But it doesn't work using the variables, even tho the parallel function validateNames() does work using the variables. I keep getting the "Not valid input" response.

What am I missing?

Re: Regex, numerals and using variables for bounds

Posted: Tue Jun 08, 2010 10:52 am
by AbraCadaver
Just a shot in the dark: is there supposed to be a space after the comma in the pattern?

Re: Regex, numerals and using variables for bounds

Posted: Tue Jun 08, 2010 10:58 am
by Weirdan
AbraCadaver wrote:Just a shot in the dark: is there supposed to be a space after the comma in the pattern?
Nice shot!

Code: Select all

weirdan@virtual-debian: ~$ php -r 'var_dump((bool)preg_match("/^[0-9]{1, 2}$/", "11"));'
bool(false)
weirdan@virtual-debian: ~$ php -r 'var_dump((bool)preg_match("/^[0-9]{1,2}$/", "11"));'
bool(true)

Re: Regex, numerals and using variables for bounds

Posted: Tue Jun 08, 2010 11:01 am
by phpBever
Brilliant. Can't imagine how good your shots would be with enought daylight. :)

That fixed it. Even confirmed the point by using the numerals rather than the variables and putting the extra space in.

Who'd'a'thunk it?

Many thanks.