1

I am trying to find a number that consists of only 8 numbers, this is the code I have already:

preg_match_all("/([0-9]{8})/", $string, $match)

but this pulls 8 numbers from number strings that are longer than 8 digits

any help would be gratefully appreciated

Thanks

5 Answers 5

5

I'll use \d rather than [0-9].

If your string should contain nothing but a number of eight digits

Use ^ and $ to match start and end of string, respectively:

preg_match_all('/^(\d{8})$/', $string, $match)

If, within a larger string, you're matching a number that should have a maximum of eight digits

Quick but slightly brutish approach:

Use \D ([^0-9]) to match "not-a-number":

preg_match_all('/^|\D(\d{8})\D|$/', $string, $match)

Lookbehinds/lookaheads might make this better:

preg_match_all('/(?<!\d)(\d{8})(?!\d)/', $string, $match)
3
  • You really don't need the match in the first example =) $string === $match[1]
    – Rudie
    Apr 20, 2011 at 13:40
  • @Rudie: Fair enough. I was only modifying the regular expression, leaving the rest of the OP's code intact. Apr 20, 2011 at 13:43
  • I know. Just saying. Gotta love the regex
    – Rudie
    Apr 20, 2011 at 13:46
4

You need word boundaries

/\b[0-9]{8}\b/

Example:

$string = '34523452345 2352345234 13452345 45357567567567 24573257 35672456';
preg_match_all("/\b[0-9]{8}\b/", $string, $match);
print_r($match);

Output:

Array
(
    [0] => Array
        (
            [0] => 13452345
            [1] => 24573257
            [2] => 35672456
        )

)
1

This might be better than the other two suggestions:

preg_match_all('/(?<!\d)(\d{8})(?!\d)/', $string, $match)

Note that \d is equivalent to [0-9].

3
  • Word-boundaries (\b) and ^ and $ are not really correct here -- this answer is better.
    – simon
    Apr 20, 2011 at 13:32
  • But this will also match words like test12345678.
    – biakaveron
    Apr 20, 2011 at 13:33
  • @biakaveron -- as I read the question, that's exactly correct!
    – simon
    Apr 20, 2011 at 13:33
0
preg_match_all("/(?:^|\D)(\d{8})(?:\D|$)/", $string, $match);

Where the start and end non-matching groups (?:) allow for any non-digit (\D) or the start (^) or end ($) of the string.

0

Maybe include anything but digits before and after.

preg_match_all("/[^\d]([\d]{8})[^\d]/", $string, $match)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.