Page 1 of 1
Strange regex behavior? Multiple spaces with \s*
Posted: Sun May 03, 2009 10:39 am
by anthonylebrun
The following validates one user data entry:
Code: Select all
if (!filter_var($_POST['name'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/\s*/")))) {
$errmsg['name'] = "<font size='1' color='red'>Everyone has a name...</font>";
$valid_form = FALSE;
}
Full code here:
http://snipt.org/Wgj
Test it here:
http://pierre-tori.com/sandbox/form.php
I mean for it to issue a warning when the user inputs nothing or whitespace.
However the regex
only matches a completely blank input field.
What gives?
Re: Strange regex behavior? Multiple spaces with \s*
Posted: Sun May 03, 2009 12:34 pm
by jazz090
you are using asterisk which suggest that whitespace may not be present: use /\s+/ instead (this validates whitespace) to validate a void entry use the empty() function.
Re: Strange regex behavior? Multiple spaces with \s*
Posted: Sun May 03, 2009 7:42 pm
by anthonylebrun
jazz090 wrote:you are using asterisk which suggest that whitespace may not be present: use /\s+/ instead (this validates whitespace) to validate a void entry use the empty() function.
Shouldn't /\s*/ cover those cases (empty, single and multiple spaces)? I tried your suggestion but the program is still exhibiting the same behavior as before.
Code: Select all
if (empty($_POST['name']) || !filter_var($_POST['name'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/\s+/")))) {
Sooo.. what gives?

Re: Strange regex behavior? Multiple spaces with \s*
Posted: Mon May 04, 2009 5:56 am
by prometheuzz
anthonylebrun wrote:...
only matches a completely blank input field.
What gives?
No, that regex wil match any string. Because any string has "zero or more white space characters" in it. You'll probably want to "anchor" the start- and end-of-line in your regex:
The regex above will match an empty string and strings containing white space characters only.
Re: Strange regex behavior? Multiple spaces with \s*
Posted: Mon May 04, 2009 6:02 am
by anthonylebrun
Oh that makes sense, thanks!
EDIT: for some reason it still doesn't match a completely blank entry (as obtained from $_POST) however adding
solved that. Anyone know why this is?
Re: Strange regex behavior? Multiple spaces with \s*
Posted: Mon May 04, 2009 6:09 am
by prometheuzz
No problem.