Page 1 of 1
PHP regular expression check
Posted: Sat Apr 30, 2011 6:16 am
by markthien
Hi guys,
I need to allow user enter only alphanumeric and !@#$%^&*()-_?<>.,
if tried the following but doesn't output correct result:
Code: Select all
$test_str = 'abc123!@';
$match = mb_ereg('^[A-Za-z0-9]$', $test_str);
if($match){
echo 'match';
} else {
echo 'not match';
}
the result said match. OMG. Please advice. Thanks in advance!
regards,
Mark
Re: PHP regular expression check
Posted: Sat Apr 30, 2011 11:05 am
by ModusPonens
Have you tried using eregi instead of mb_ereg?
If that doesn't work, you can always inspect the individual contents of the string array for ascii values using ord($string). If you didn't know, PHP implicitly creates an array out of any string value. If you've ever written any C++, you'll understand why.
$name = "brian";
echo $name[0];
echo $name[1];
echo $name[2];
echo $name[3];
echo $name[4];
Output will be brian
Looks to me like the range you want to test falls within ASCII values of 33 through 123, inclusive.
so, stepping through the string array $name
echo ord($name[0])." ";
echo ord($name[1])." ";
echo ord($name[2])." ";
echo ord($name[3])." ";
echo ord($name[4])." ";
output will be 98 114 105 97 110
The benefit of doing it this way is that on the failure of a particular character within the string, you can report back to the client where they screwed up. Reporting back to the client "You've made a mistake entering data into XYZ field" is a crappy error message. Telling them "You've entered a ' ".$name[$i]." ' in XYZ field - this character is not allowed, please try again" is more user friendly.
This isn't as elegant of a solution as eregi, but it's certainly easier to read, and I'm all for writing code that a newbie could read whenever I can. You never know who's going to come behind you and have to modify something you did.
I'm relatively new to PHP, but I first learned how to program in 1986. A valuable lesson I learned way back then was to always assume that your user has an IQ of 80. My validation is probably bulkier than necessary under most circumstances, but there's nothing I hate more than getting a meaningless error message.
Re: PHP regular expression check
Posted: Sat Apr 30, 2011 11:28 am
by koen.h
The ^ and $ are special characters in double quoted strings, not in single quoted.
Re: PHP regular expression check
Posted: Sat Apr 30, 2011 10:56 pm
by Jonah Bron
all
(*_)ereg(i) functions are depreciated. Use
preg_match() instead.
Code: Select all
$valid = !preg_match('/[^\d!@#\$%^&*()-_?<>\.,]/', $string);
if ($valid) {
echo 'good';
} else {
echo 'bad';
}
The exclamation mark there inverts the boolean value. The regex checks for any bad characters. If they're there, it returns true (which is reversed by the ! to false), giving us the value of $valid.
Re: PHP regular expression check
Posted: Sun May 01, 2011 8:58 am
by ModusPonens
Good catch. Forgot about that.