2016-11-04 50 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