Sami Posted August 20, 2011 Share Posted August 20, 2011 Hi.Is there a way I can validate that a string only contains letters and numbers? Link to comment Share on other sites More sharing options...
Ingolme Posted August 20, 2011 Share Posted August 20, 2011 It uses regular expressions.Just search for any character that's not a letter or number. $str = 'A string';if(!preg_match('/[^a-zA-Z0-9]/',$str)) { // This string is valid} else { // This string is not valid} Regular expressions may be complicated to understand at first. Check http://regularexpressions.info and PHP's manual: http://php.net/preg_match Link to comment Share on other sites More sharing options...
Sami Posted August 21, 2011 Author Share Posted August 21, 2011 It uses regular expressions.Just search for any character that's not a letter or number.$str = 'A string';if(!preg_match('/[^a-zA-Z0-9]/',$str)) { // This string is valid} else { // This string is not valid} Regular expressions may be complicated to understand at first. Check http://regularexpressions.info and PHP's manual: http://php.net/preg_match Thanks! But can I make 'æ', 'ø' and 'å' valid using that code? Forgot to mention that x) Link to comment Share on other sites More sharing options...
Ingolme Posted August 22, 2011 Share Posted August 22, 2011 Yes, you just need to add them to the regular expression. /[^a-zA-Z0-9æøå]/Character encoding might be a problem, though, you can use the unicode number of the character like this:/[^a-zA-Z0-9\u####\u####\u####]/Substitutung the # for the character number. Link to comment Share on other sites More sharing options...
Sami Posted August 23, 2011 Author Share Posted August 23, 2011 Yes, you just need to add them to the regular expression. /[^a-zA-Z0-9æøå]/Character encoding might be a problem, though, you can use the unicode number of the character like this:/[^a-zA-Z0-9\u####\u####\u####]/Substitutung the # for the character number.I guess this character encoding problem gone if I use UTF-8 ?It doesn't work btw. Everything becomes invalid. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.