[英]Using preg_match to validate a string format
I have an html form with an input for a sales order number which should have the format of K1234/5678. 我有一个带有销售订单号输入的html表单,该订单的格式应为K1234 / 5678。 It should always start with the letter K then 4 numbers, a / and followed by another set of 4 numbers. 它应始终以字母K开头,然后是4个数字,一个/,然后是另一组4个数字。
I'm trying to validate the formatting using preg_match and I'm getting lost in the syntax of preg_match. 我正在尝试使用preg_match验证格式,但是我迷失了preg_match的语法。 From http://php.net/manual/en/function.preg-match.php I've gotten close. 从http://php.net/manual/en/function.preg-match.php开始,我已经接近了。 With the following code I'm able to verify that it contains at least 1 letter, some numbers and at least 1 non- alphanumeric value. 使用以下代码,我可以验证它是否包含至少1个字母,一些数字和至少1个非字母数字值。
$so= $_POST['so'];
if (preg_match(""/^(?=.*[a-z]{1})(?=.*[0-9]{4})(?=.*[^a-z0-9]{1})/i", $so))
{
print $so;
}
What is the correct syntax to use for this? 正确的语法是什么? Is preg_match even the best way to do this? preg_match甚至是最好的方法吗?
Try this: 尝试这个:
preg_match("#^K[0-9]{4}/[0-9]{4}$#i", $so)
Explanation: 说明:
The #
characters are regular expression delimiters - they indicate the start/end of the pattern. #
字符是正则表达式定界符-它们指示模式的开始/结束。 The ^
and $
indicate the start and end of the string - this means that it will only match if your sales order number is the only thing in the string. ^
和$
表示字符串的开头和结尾-这意味着只有在字符串中唯一的销售订单号时,该字符串才会匹配。 The letter K
means match that letter, [0-9]{4}
means match a digit exactly 4 times. 字母K
表示与该字母匹配, [0-9]{4}
表示与一个数字精确匹配4次。 The i
at the end means a case-insensitive match - the K
will match either "K" or "k". 最后的i
表示不区分大小写的匹配K
将匹配“ K”或“ k”。
When developing regular expressions, I often use regular expression testers - these allow you to enter your data and try a bunch of different things to refine your regex. 在开发正则表达式时,我经常使用正则表达式测试器-这些测试器可让您输入数据并尝试各种不同的操作来完善正则表达式。 Google PHP regex tester to find a list of tools. Google PHP正则表达式测试器 ,可找到工具列表。 Also, there's a very complete reference to regular expressions at http://www.regular-expressions.info/ . 另外,在http://www.regular-expressions.info/上有对正则表达式的非常完整的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.