开发者

How to match a fixed number of digits with regex in PHP?

开发者 https://www.devze.com 2022-12-24 06:36 出处:网络
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社区).

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

0

精彩评论

暂无评论...
验证码 换一张
取 消