Martin1184
Martin1184

Reputation: 17

I need help applying a limit to a Regular expression on php

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

Upvotes: 1

Views: 139

Answers (5)

radios4rabbits
radios4rabbits

Reputation: 33

Maybe include anything but digits before and after.

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

Upvotes: 0

simon
simon

Reputation: 16300

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].

Upvotes: 1

ADW
ADW

Reputation: 4080

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.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

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)

Upvotes: 5

John Giotta
John Giotta

Reputation: 16944

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
        )

)

Upvotes: 4

Related Questions