2011-07-17 84 views
1

即使我輸入的電話號碼無效,我的正則表達式也會驗證它並顯示有效的消息。任何想法最新怎麼了?正則表達式驗證不起作用(電話和姓名)

<form action="<?php $PHP_SELF; ?>" method="POST"> 
Name (First Middlie Last) : <input type="text" name="name" value=""><br /> 
Telephone Number : <input type="text" name="phone" value=""><br /> 
<input type="submit"> 
</form> 

<?php } else { 

extract($_REQUEST); 

$phoneDashes = preg_replace("/\D/","", $phone); 
$nameRegex = $_POST['name']; 

if(preg_match("/(\d{3})(\d{3})(\d{4})/", $phoneDashes,$matches)) { 
echo "Valid phone number <br />"; 
    } 
else { 
    echo "Not a valid phone number <br />"; 
} 

preg_match("/(^[\-a-z]+)\s([\-a-z])\s([\-a-z]+)$/i", $nameRegex,$names); 

echo "Your name: $names[3], $names[2] $names[1] <br />"; 
echo "Your phone Number: $matches[1]-$matches[2]-$matches[3] <br />"; 

} 

?> 
+0

你在'if'語句中使用了什麼字符串? – VMAtm

+0

電話號碼字符串?問題在哪裏? – harry

+0

不,你用什麼值得到錯誤的結果? – VMAtm

回答

1

嘗試

$match = preg_match("/(\d{3})(\d{3})(\d{4})/", $phoneDashes,$matches); 
if($match) { 
echo "Valid phone number <br />"; 
    } 
else { 
    echo "Not a valid phone number <br />"; 
} 
+0

mmm ..不行,也不起作用。無論我輸入什麼,它都會顯示有效的號碼。還有什麼建議?謝謝你的幫助。 – harry

+0

http://sandbox.phpcode.eu/g/4ef02.php?phone=1234567891作品 – genesis

+0

回答編輯。現在試試 – genesis

0

你需要^$錨。試試這個:

if (preg_match('/^(\d{3})(\d{3})(\d{4})$/', $phoneDashes, $matches)) 
    // Valid phone number 
else 
    // Not valid phone number 
相關問題