Regex, numerals and using variables for bounds

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

Regex, numerals and using variables for bounds

Post 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?
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Regex, numerals and using variables for bounds

Post by AbraCadaver »

Just a shot in the dark: is there supposed to be a space after the comma in the pattern?
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Regex, numerals and using variables for bounds

Post 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)
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

Re: Regex, numerals and using variables for bounds

Post 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.
Post Reply