php code to validate alphanumeric string

时光毁灭记忆、已成空白 提交于 2019-12-19 06:11:59

问题


I want to validate alphanumeric string in form text box in php. It can contain numbers and special characters like '.' and '-' but the string should not contain only numbers and special characters. Please help with the code.


回答1:


Try this

// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
    // Valid
} else {
    // Invalid
}



回答2:


Use ctype_alnum like below:

if(ctype_alnum($string)){
    echo "Yes, It's an alphanumeric string/text";
}
else{
    echo "No, It's not an alphanumeric string/text";
}

Read function specification on php.net




回答3:


Code:

if(preg_match('/[^a-z_\-0-9]/i', $string)) { echo "not valid string"; }

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z




回答4:


I'm sort of new to regex, but I would do it this way:

preg_match('/^[\w.-]+$/', input)


来源:https://stackoverflow.com/questions/15920360/php-code-to-validate-alphanumeric-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!