2016-11-04 52 views
0

在使用php驗證正則表達式時遇到問題。php正則表達式問題

我有一個html表格,要求輸入電話號碼,車牌,街道地址,生日和社會保險號碼。 (我只用獲得的電話號碼和街道爲現在可以正常工作而言)

我需要使用的preg_match功能要堅持以下標準電話號碼:

電話號碼 - 7位或10位數字

◦7數字:前三個數字是一個基團,並且可以從最終四位以短劃線,一個或多個空格,或什麼都沒有

◦10數字來分離:fi前三位數字,後三位數字和最後四位數字是三個不同的組,並且每組可以通過無,短劃線或一個或多個空格或括號與其相鄰組分隔開。所有這些都是有效的 ▪(604)123-4567,但不是604)123-4567,而不是(604123-4567 ▪6041234567 ▪1234567 ▪123-4567 ▪1234567 ▪604-123-4567 ▪ 604 123 4567 ▪6041234567 ▪604123456

我需要使用的preg_match功能要堅持以下標準電話號碼:

街道地址 - 三到五年號地址後面的字符串,必須以「Street」結尾◦eg。這些都是有效的 ▪123大街 ▪8888橡樹街 ▪55555繆爾街

到目前爲止的代碼爲lab11.html和lab11.php lab11.html

<!DOCTYPE html> 
<html> 
<head> 
<title>Lab 11</title> 
<meta charset="utf-8"> 
</head> 
<body> 
<form action="lab11.php" method="POST"> 
<input type="text" name="phoneNumber"placeholder="Phone Number" style="font-size: 15pt"> 
<br> 
<input type="text"name="licensePlate"placeholder="License Plate" style="font-size: 15pt"> 
<br> 
<input type="text" name="streetAddress" placeholder="Street Address" style="font-size: 15pt"> 
<br> 
<input type="text" name="birthday" placeholder="Birthday" style="font-size: 15pt"> 
<br> 
<input type="text" name="socialInsuranceNumber" placeholder="Social Insurance Number" style="font-size: 15pt"> 
<br> 
      <input type="submit" name="submit" value="Submit"> 
</form> 
</body> 
</html> 

lab11.php

<?php 
    // Get phone number, license plate, street address, birthday and 
    // social insurance number entered from lab11.html form 
    $phoneNumber = $_POST['phoneNumber']; 
     echo "Your phone number is " . $phoneNumber; 
     echo "<br>"; 
    $licensePlate = $_POST['licensePlate']; 
     echo "Your License Plate Number is " . $licensePlate; 
     echo "<br>"; 
    $streetAddress = $_POST['streetAddress']; 
     echo "Your Street Address is " . $streetAddress; 
     echo "<br>"; 
    $birthday = $_POST['birthday']; 
     echo "Your Birthday is " . $birthday; 
     echo "<br>"; 
    $socialInsuranceNumber = $_POST['socialInsuranceNumber']; 
     echo "Your Social Insurance Number is " . $socialInsuranceNumber; 

    echo "<br>"; 

    // Validate regular expression for phone number entered 
    if (preg_match("/^\(.[0-9]{3}[0-9]$/", $phoneNumber)) { 
     echo "Your phone is correct."; 
    } 
    else { 
     echo "Your password is wrong."; 
    } 
    // Validate regular expression for license plate entered 
    if (preg_match("/{3,5}.String$/", $streetAddress)) { 
     echo "Your plate is correct."; 
    } 
    else { 
     echo "Your plate is wrong."; 
    } 
?> 

回答

0

正則表達式的電話號碼:

^(\([\d]{3}\)|[\d]{3})?(-|\s*)?([\d]{3})?(-|\s*)?[\d]{3}(-|\s*)?[\d]{4}$ 

和地址:

^([\d]{3,5})\s+[a-zA-Z'"\s]+\s*Street$ - you can add `i` modifier for case insensitive 

[a-zA-Z'"\s] - 只給字母+「」白色空間 - 街道名稱。根據您的需要,您可以修改它

+0

這將接受'++++ _______ Street'作爲有效地址!和'+++++++++++++'作爲有效的電話號碼 – Toto

+0

感謝您的評論!我修正了這個錯誤。 – krasipenkov