PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
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.
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.
Last edited by ModusPonens on Sat Apr 30, 2011 11:29 am, edited 1 time in total.
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.