如何在PHP的preg_match中精确匹配3位数字? [英] How to match exactly 3 digits in PHP's preg_match?

查看:544
本文介绍了如何在PHP的preg_match中精确匹配3位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说您具有以下值:

Lets say you have the following values:

123
1234
4567
12
1

我正在尝试纠正preg_match,该匹配将仅对'123'返回true,因此仅在3位数字时匹配.这就是我所拥有的,但它也与1234和4567相匹配.在它之后我可能还会有一些东西.

I'm trying to right a preg_match which will only return true for '123' thus only matching if 3 digits. This is what I have, but it is also matching 1234 and 4567. I may have something after it too.

preg_match('/[0-9]{3}/',$number);

推荐答案

您需要的是 anchors :

preg_match('/^[0-9]{3}$/',$number);

它们表示字符串的开头和结尾.您之所以需要它们,是因为通常正则表达式匹配会尝试在主题中找到任何匹配的子字符串.

They signify the start and end of the string. The reason you need them is that generally regex matching tries to find any matching substring in the subject.

正如rambo编码器所指出的,如果最后一个字符是换行符,则$也可以在字符串的最后一个字符之前匹配.要更改此行为(以使456\n不会导致匹配),请使用D修饰符:

As rambo coder pointed out, the $ can also match before the last character in a string, if that last character is a new line. To changes this behavior (so that 456\n does not result in a match), use the D modifier:

preg_match('/^[0-9]{3}$/D',$number);

或者,使用\z总是匹配字符串的末尾,而不考虑修饰符(感谢Ωmega):

Alternatively, use \z which always matches the very end of the string, regardless of modifiers (thanks to Ωmega):

preg_match('/^[0-9]{3}\z/',$number);

您说过我可能还会有其他东西".如果这意味着您的字符串应以三位数字开头,但之后可以有任何内容(只要不是其他数字),则应使用负数前瞻:

You said "I may have something after it, too". If that means your string should start with exactly three digits, but there can be anything afterwards (as long as it's not another digit), you should use a negative lookahead:

preg_match('/^[0-9]{3}(?![0-9])/',$number);

现在它也将匹配123abc.可以使用负向后看法将同样的内容应用于正则表达式的开头(如果abc123def应该给出匹配项):

Now it would match 123abc, too. The same can be applied to the beginning of the regex (if abc123def should give a match) using a negative lookbehind:

preg_match('/(?<![0-9])[0-9]{3}(?![0-9])/',$number);

进一步了解环视断言.

这篇关于如何在PHP的preg_match中精确匹配3位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆