pengu Posted June 23, 2010 Share Posted June 23, 2010 Hi guys. Quick question, couldn't find any examples on php.net. I want to do a check to see if a $variable has alphanumeric characters, if it does not, spit an error at them. <?php $team_name = 'hello01'; if (!preg_match('[a-zA-Z0-9]',$team_name)) { echo "Team Name must contain alphanumeric characters."; exit(); } ?> This still gives me the error message, can you not use '!' with preg_match? Quote Link to comment Share on other sites More sharing options...
afrojojo Posted June 23, 2010 Share Posted June 23, 2010 Try this: if (ereg('[^A-Za-z0-9]', $text)) { echo "This contains characters other than letters and numbers"; } else { echo "This contains only letters and numbers"; } Quote Link to comment Share on other sites More sharing options...
premiso Posted June 23, 2010 Share Posted June 23, 2010 Right, let's use a depreciated, or being depreciated function (IE ereg). Here is the corrected preg equivalent: if (preg_match('~[^A-Z0-9]~i', $text)) { echo "This has non alpha numeric characters"; } Quote Link to comment Share on other sites More sharing options...
Alex Posted June 23, 2010 Share Posted June 23, 2010 Or use ctype_alnum which doesn't have all the overhead of the PCRE engine. Quote Link to comment Share on other sites More sharing options...
pengu Posted June 23, 2010 Author Share Posted June 23, 2010 afrojojo - Your way worked. But it's not how I wanted to handle my errors. Thank you Premiso & AlexWD. Quote Link to comment Share on other sites More sharing options...
afrojojo Posted June 23, 2010 Share Posted June 23, 2010 I guess I should update that one. Quote Link to comment Share on other sites More sharing options...
Ruzzas Posted June 23, 2010 Share Posted June 23, 2010 pengu, Not much of a difference but you can use: die("Team Name must contain alphanumeric characters."); instead of echo and exit Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.