在PHP中,如何验证用户输入,如下例所示。
示例有效输入
$input ='abkc32453';
$input ='a32453';
$input ='dsjgjg';
示例无效输入
$input ='2sdf23';
$input ='2121adsasadf';
$input ='23142134';
答案 0 :(得分:6)
if(ctype_alpha($input[0])){
//first character is alphabet
}
else {
//first character is invalid
}
答案 1 :(得分:4)
if (preg_match('/^[a-z]/i', $input)) { /* "/i" means case independent */
...
}
或使用[:alpha:]
如果您不想使用[a-z]
(例如,如果您需要识别重音字符)。
答案 2 :(得分:3)
您可以尝试使用preg_match()
函数的正则表达式:
if (preg_match('/^[a-zA-Z]/', $input)) {
// input is OK : starts with a letter
}
基本上,您搜索:
^
[a-zA-Z]
答案 3 :(得分:2)
preg_match('%^[a-zA-Z].*%', $input, $matches);