正則表達式在匹配字符串時,遵循以下2個基本原則:
1.最左原則:正則表達式總是從目標字符串的最左側開始,依次匹配,直到匹配到符合表達式要求的部分,或直到匹配目標字符串的結束。
2.最長原則:對於匹配到的目標字符串,正則表達式總是會匹配到符合正則表達式要求的最長的部分
驗證是否是手機號碼的正則表達式
- function preg_mobile($mobile) {
- if(preg_match("/^1[34578]\d{9}$/", $mobile)) {
- return TRUE;
- } else {
- return FALSE;
- }
- }
驗證身份證號(15位或18位數字)
//驗證身份證號(15位或18位數字) function preg_idcard($idcard) { if(preg_match("/^\d{15}|\d{18}$/", $idcard)) { return TRUE; } else { return FALSE; } }
騰訊QQ號驗證
function preg_qq($qq) { if(preg_match("/^[1-9][0-9]{4,}$/", $qq)) { return TRUE; } else { return FALSE; } }
驗證Email
function preg_email($email) { if(preg_match("/^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $email)) { return TRUE; } else { return FALSE; } }
用戶名驗證:
用戶名驗證規則:用戶名只能由數字、字母、中文漢字及下划線組成,不能包含特殊符號。
function preg_email($user) {
if(preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]+$/u',$string)) {
return TRUE;
}else{
return FALSE;
}
}