Reputation: 17
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
Reputation: 33
Maybe include anything but digits before and after.
preg_match_all("/[^\d]([\d]{8})[^\d]/", $string, $match)
Upvotes: 0
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
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
Reputation: 385174
I'll use \d
rather than [0-9]
.
Use ^
and $
to match start and end of string, respectively:
preg_match_all('/^(\d{8})$/', $string, $match)
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
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