How to match exactly 3 digits in PHP preg_match?

Suppose you have the following values:

123 1234 4567 12 1 

I am trying to change preg_match which will return true only for '123', thus only matching if 3 digits. This is what I have, but it also corresponds to 1234 and 4567. Perhaps I also have something.

 preg_match('/[0-9]{3}/',$number); 
+7
source share
3 answers

You need anchors :

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

They indicate the beginning and end of a line. The reason you need them is because in the general case, regular expression matching tries to find any substring in the subject.

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

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

As an alternative, use \z , which always matches the very end of the line, regardless of modifiers (thanks to Ξ©mega):

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

You said, "Maybe I have something too." If this means that your line should start with exactly three digits, but after that there may be something (as long as it is not another digit), you should use a negative lookup:

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

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

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

Further reading of the statements about the search.

+19
source

You need to bind regex

 /^\d{3}$/ 
+4
source

If you are looking for a three-digit number anywhere in the text, use the regex pattern

 /(?<!\d)\d{3}(?!\d)/ 

However, if you check the entry as a 3-digit number and nothing else, go to

 /\A\d{3}\z/ 
+3
source

All Articles