简体   繁体   English

PHP-正则表达式匹配这样的字符串:2012/018843/06?

[英]PHP - Regular expressions to match a string like this : 2012/018843/06?

I do not know very much about regular expressions but would like to create a regex to validate a string like this: `2012/018843/06. 我对正则表达式不是很了解,但是想创建一个正则表达式来验证这样的字符串:`2012/018843/06。

If it may help someone in the future, I would like to say that would be for a South African Company Registration Number. 如果将来对某人有帮助,我想说的是南非公司注册号。

If anyone would be kind enough to post a regex that can be processed via PHP and does match this, that would be great. 如果有人愿意发布可以通过PHP处理并与之匹配的正则表达式,那就太好了。 If not, any links to "the basics" of creating regular expressions in this manner would be much appreciated! 如果不是这样,那么以这种方式创建正则表达式的“基础”的任何链接将不胜感激!

Thanks. 谢谢。

EDIT: 编辑:

I have tried this: 我已经试过了:

[0-9/]{14}

But it does not match the length exactly. 但是它与长度不完全匹配。

In it's simplest form: 以最简单的形式:

preg_match("|^\d{4}/\d{6}/\d{2}$|", $input);

The \\d token matches any integer 0 - 9, the integer inside {} indicates how many repetition are allowed from the previous tokens, the / matches literal / since I'm using | \\d令牌与任何0到9的整数匹配, {}内的整数表示以前的令牌允许重复多少次, /匹配文字/因为我正在使用| as the regex delimiter. 作为正则表达式分隔符。

The ^ token is to match from the beginning of the string, and $ to match the end of string, this way, things like aa2012/124521/11bb won't match (it would match otherwise if you take out the ^$ ) ^令牌是从字符串的开头开始匹配, $是从字符串的末尾开始匹配,这样,诸如aa2012/124521/11bb将不匹配(否则,如果您取出^$则将匹配)

are the numerics fixed in length? 数字固定长度吗? then try 然后尝试

preg_match('#^\d{4}/\d{6}/\d{2}$#', $string)

syntax: 句法:

  • \\d is an escape sequence which represents any decimal digit (0-9), this could also be represented by [0-9] \\d是一个转义序列,表示任何十进制数字(0-9),也可以由[0-9]表示
  • {4} defines, that the last expression (in this case: a decimal digit) has to occur 4 times, using this expression avoids repeating the previous expression many times, so \\d{4} means \\d\\d\\d\\d {4}定义最后一个表达式(在本例中为十进制数字)必须出现4次,使用此表达式可避免多次重复前一个表达式,因此\\d{4}表示\\d\\d\\d\\d
  • ^ represents the beginning of the string and $ the end of the string, so this ensures, that there are no other chars in this string, so a string like abc2012/018843/06def would not match ^表示字符串的开头, $表示字符串的结尾,因此可以确保此字符串中没有其他字符,因此abc2012/018843/06def类的字符串将不匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM