darkhappy Posted May 17, 2008 Share Posted May 17, 2008 How can I check $var for characters 0 - 9 and a -z (and what ohter normal charactes should I look for?)? I am processing a value from a CSV file if I run the check if ($var!='') on some of the fields it returns TRUE even though the CSV field is empty, so I need to check the $var to make sure it contains data. Please let me know if this question does not make sense so I can re-phrase or give more info. Thank you, dhappy Quote Link to comment https://forums.phpfreaks.com/topic/106064-check-string-for-chars/ Share on other sites More sharing options...
Orio Posted May 17, 2008 Share Posted May 17, 2008 Best solution for you would be using ctype_alnum(). It's more efficient than using a regular expression, and it does the job. The regex way: <?php if(preg_match("/^[a-z0-9]*$/i", $str)) { //$str is valid } ?> Orio. Quote Link to comment https://forums.phpfreaks.com/topic/106064-check-string-for-chars/#findComment-543596 Share on other sites More sharing options...
darkhappy Posted May 17, 2008 Author Share Posted May 17, 2008 great - thanks so much. Quote Link to comment https://forums.phpfreaks.com/topic/106064-check-string-for-chars/#findComment-543746 Share on other sites More sharing options...
darkhappy Posted May 17, 2008 Author Share Posted May 17, 2008 Best solution for you would be using ctype_alnum(). It's more efficient than using a regular expression, and it does the job. The regex way: <?php if(preg_match("/^[a-z0-9]*$/i", $str)) { //$str is valid } ?> Orio. I have tried both ways and empty fields are still evaluating to true. What am I doing wrong? Here is my code: <?php foreach($checkarr1 as $v4) { if(ctype_alnum($v4)) { echo "'".$v4."'-"; } } ?> $checkarr1 is an array created from a row in a CSV file, some values are null and I only want to echo $v4 for valid fields. I put '' around the var so I can see the blanks when it outputs. thanks, dhappy Quote Link to comment https://forums.phpfreaks.com/topic/106064-check-string-for-chars/#findComment-543789 Share on other sites More sharing options...
sasa Posted May 18, 2008 Share Posted May 18, 2008 <?php if(preg_match("/^[a-z0-9]+$/i", $str)) { //$str is valid } ?> Quote Link to comment https://forums.phpfreaks.com/topic/106064-check-string-for-chars/#findComment-543996 Share on other sites More sharing options...
Orio Posted May 18, 2008 Share Posted May 18, 2008 Missed your comment about the empty fields. Here's the ctype_alnum() fix. sasa's solution would, of course, also work. <?php foreach($checkarr1 as $v4) { if(!empty($v4) && ctype_alnum($v4)) echo "'".$v4."'-"; } ?> Orio. Quote Link to comment https://forums.phpfreaks.com/topic/106064-check-string-for-chars/#findComment-544021 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.