godsent Posted January 9, 2010 Share Posted January 9, 2010 Is where any way to check if string contains only a-z/A-Z, without writing an array with all possible letters and then looping it. $available = array('a', 'b', 'c, 'd'); //write a-z for ($i = 0; $i <= count($available); $i++) { $string = str_replace($available[$i], "", $string); } if ($string != "") { print "Illegal character."; } Quote Link to comment https://forums.phpfreaks.com/topic/187881-check-if-string-contain-only-a-za-z/ Share on other sites More sharing options...
laffin Posted January 9, 2010 Share Posted January 9, 2010 if(!preg_match('/^[a-z]+$/i',$string)) echo 'Illegal characters'; Quote Link to comment https://forums.phpfreaks.com/topic/187881-check-if-string-contain-only-a-za-z/#findComment-991964 Share on other sites More sharing options...
godsent Posted January 9, 2010 Author Share Posted January 9, 2010 can PHP see difference between capital letters (B and b), will this show capital letters as illegal? Quote Link to comment https://forums.phpfreaks.com/topic/187881-check-if-string-contain-only-a-za-z/#findComment-991969 Share on other sites More sharing options...
Alex Posted January 9, 2010 Share Posted January 9, 2010 A better alternative would be to use ctype_alpha, preg_match uses a lot more resources and it's unnecessary in this case. Example: if(!ctype_alpha($string)) { // Contains illegal characters } [ot]In your example you did this: $available = array('a', 'b', 'c', 'd'); //write a-z If you actually needed to create an array of a-z you could do: $arr = range('a', 'z'); [/ot] Quote Link to comment https://forums.phpfreaks.com/topic/187881-check-if-string-contain-only-a-za-z/#findComment-991973 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.