我有一个表格,用户可以输入车牌号码。提交表格后,我想检查用户提供的牌照是否具有某种格式,例如,我想只允许他们提交,如果格式是以下任何一种格式:
example license plate "1SAM123" (1 number, 3 letters, 3 numbers)
example license plate "82739F1" (5 numbers, 1 letter, 1 number)
example license plate "8U89238" (1 number, 1 letter, 5 numbers)
example license plate "445112" (six digit numbers only)
我尝试使用substr来获取字符串的每个字符,然后检查每个字符
$plate1 = substr($plate, 0, 1);
$plate2 = substr($plate, 1, 1);
$plate3 = substr($plate, 2, 1);
$plate4 = substr($plate, 3, 1);
$plate5 = substr($plate, 4, 1);
$plate6 = substr($plate, 5, 1);
$plate7 = substr($plate, 6, 1);
然而我似乎无法检查这些是否是整数,因为substr使它们像一个字符串,如果有更好的方法这样做我会很感激谢谢
答案 0 :(得分:1)
试试这个:
<?php
checkPlate('1SAM123');
checkPlate('82739F1');
checkPlate('8U89238');
checkPlate('445112');
checkPlate('01234FF');
checkPlate('44511200');
function checkPlate($plate) {
echo $plate . " is " . (isValidPlate($plate) ? "valid\n" : "invalid\n");
}
function isValidPlate($plate) {
foreach(array(array(1, 3, 3),
array(5, 1, 1),
array(1, 1, 5),
array(6, 0, 0)) as $i) {
$matches = array();
preg_match("/[0-9]{{$i[0]}}[A-Z]{{$i[1]}}[0-9]{{$i[2]}}+/", $plate, $matches);
if (isset($matches) && $matches[0] == $plate)
return true;
}
return false;
}
1SAM123 is valid
82739F1 is valid
8U89238 is valid
445112 is valid
01234FF is invalid
44511200 is invalid
答案 1 :(得分:0)
您可以使用正则表达式。 PHP使用PCRE(Perl兼容正则表达式)。下面提供的示例与您正在寻找的内容相匹配......
$strings = [
"1SAM123",
"82739F1",
"8U89238",
"445112",
"This will not match...",
];
foreach($strings as $string) {
if (preg_match("#(\d[a-z]{3}\d{3})|(\d{5}[a-z]\d)|(\d[a-z]\d{5})|(\d{6})#i", $string)) {
echo "The string '$string' matches our expression!";
}
}
答案 2 :(得分:0)
您可以使用正则表达式preg_match。
就像这样:
$pattern = "/[0-9]{1}[A-Za-z]{3}[0-9]{3}|[0-9]{5}[A-Za-z]{1}[0-9]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{5}|[0-9]{6}/";
if (preg_match($pattern, $plate_number) === false) {
// Not valid
} else {
// Valid
}
但是这个是一个例子而且很长,所以你需要提出一个更好的正则表达式来验证你的数据。