How to match a fixed number of digits with regex in PHP?
I want to retrieve the consecutive 8 digits out of a string.
"hello world,12345678anything else"
should return 12345678
as result(the space in between is optional开发者_StackOverflow社区).
But this should not return anything:
"hello world,123456789anything else"
Because it has 9 digits,I only need 8 digits unit.
Try
'/(?<!\d)\d{8}(?!\d)/'
$var = "hello world,12345678798anything else";
preg_match('/[0-9]{8}/',$var,$match);
echo $match[0];
You need to match the stuff on either side of the 8 digits. You can do this with zero-width look-around assertions, as exemplified by @S Mark, or you can take the simpler route of just creating a backreference for the 8 digits:
preg_match('/\D(\d{8})\D/', $string, $matches)
$eight_digits = $matches[1];
But this won't match when the digits start or end a line or string; for that you need to elaborate it a bit:
preg_match('/(?:\D|^)(\d{8})(?:\D|$)/', $string, $matches)
$eight_digits = $matches[1];
The (?:...)
in this one allows you to specify a subset of alternates, using |
, without counting the match as a back-reference (ie adding it to the elements in the array $matches
).
For many more gory details of the rich and subtle language that is Perl-Compatible Regular Expression syntax, see http://ca3.php.net/manual/en/reference.pcre.pattern.syntax.php
精彩评论