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.
Martin ender
source share