[英]regex validation not parsing string in if PHP
Here is the deal... 这是交易...
I am suppose to parse a Canadian Postal Code (CapsLetterNumberCapsLetterNumberCapsLetterNumber: exemple A1B2C3 or G2V3V4) IF there is one. 我想解析一个加拿大邮政编码(CapsLetterNumberCapsLetterNumberCapsLetterNumber:例如A1B2C3或G2V3V4),如果有的话。
I have this code (PHP): 我有以下代码(PHP):
//Create new SESSION variable to store a warning
$_SESSION['msg'] = "";
//IF empty do nothing, IF NOT empty parse, IF NOT match regex put message in msg
if(!preg_match('^([A-Z][0-9][A-Z][0-9][A-Z][0-9])?$^', $_POST['txtPostalCode']) && $_POST['txtPostalCode'] != "")
{
$_SESSION['msg'] .= "Warning invalide Postal Code";
}
then the code goes on to display $_SESSION['msg']
. 然后代码继续显示
$_SESSION['msg']
。
The problem is that whatever I enter in $_POST['txtPostalCode'] it NEVER get parse by the REGEX. 问题是,无论我在$ _POST ['txtPostalCode']中输入什么,它都不会被REGEX解析。
You made the entire capturing group optional: 您将整个捕获组设为可选:
^([A-Z][0-9][A-Z][0-9][A-Z][0-9])?$^
^
It's also not a good idea to use regex metadata characters as your delimiter. 使用正则表达式元数据字符作为分隔符也不是一个好主意。 Try this regex, which matches an uppercase letter and a number three times:
尝试使用此正则表达式,该正则表达式将一个大写字母和一个数字匹配三遍:
/^((?:[A-Z][0-9]){3})$/
You don't need to make the capturing group optional because you handle the logic for when the user doesn't submit a code with the && $_POST['txtPostalCode'] != ""
part of the if statement. 您不需要将捕获组设为可选,因为您可以处理if语句中
&& $_POST['txtPostalCode'] != ""
用户未提交代码时的逻辑。
Finally, since you're not even using the matches from this regex, you don't need the capturing group: 最后,由于您甚至没有使用此正则表达式中的匹配项,因此不需要捕获组:
/^(?:[A-Z][0-9]){3}$/
Your regex will match invalid postal codes. 您的正则表达式将匹配无效的邮政编码。
A quick Google search for "canadian postal code regex" bought up 快速谷歌搜索“加拿大邮政编码的正则表达式” 买涨
^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
You may also want to put your $_POST['txtPostalCode'] != ""
condition first since there's no point in executing a regex if the value is empty to begin with. 您可能还想先设置
$_POST['txtPostalCode'] != ""
条件,因为如果值开头为空,则执行正则表达式毫无意义。
Edit: As pointed out by the comments, the quantifiers are redundant: 编辑:正如评论所指出的,量词是多余的:
^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.