简体   繁体   English

如何在PHP中使用正则表达式匹配固定数量的数字?

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

I want to retrieve the consecutive 8 digits out of a string. 我想从字符串中检索连续的8位数。

"hello world,12345678anything else"

should return 12345678 as result(the space in between is optional). 应该返回12345678 (两者之间的空格是可选的)。

But this should not return anything: 但这不应该返回任何东西:

"hello world,123456789anything else"

Because it has 9 digits,I only need 8 digits unit. 因为它有9位数,所以我只需要8位数单位。

尝试

'/(?<!\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. 你需要匹配8位数字两边的东西。 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: 您可以使用零宽度环视断言来实现此操作,例如@S Mark,或者您可以采用更简单的方法来创建8位数的反向引用:

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 ). ,不将匹配计为反向引用(即将其添加到数组$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 有关Perl兼容正则表达式语法的丰富和微妙语言的更多详细信息,请参阅http://ca3.php.net/manual/en/reference.pcre.pattern.syntax.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM