Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php preg_match返回最长的比赛_Php_Regex_Preg Match - Fatal编程技术网

Php preg_match返回最长的比赛

Php preg_match返回最长的比赛,php,regex,preg-match,Php,Regex,Preg Match,我试图返回一系列5到9位数的数字。我希望能够获得尽可能长的匹配,但不幸的是preg_match只返回匹配的最后5个字符 $string = "foo 123456"; if (preg_match("/.*(\d{5,9}).*/", $string, $match)) { print_r($match); }; 将产生结果 Array ( [0] => foo 123456 [1] => 23456 ) 使用像*? <?php $string = "foo 123

我试图返回一系列5到9位数的数字。我希望能够获得尽可能长的匹配,但不幸的是preg_match只返回匹配的最后5个字符

$string = "foo 123456";
if (preg_match("/.*(\d{5,9}).*/", $string, $match)) {
    print_r($match);
};
将产生结果

Array
(
[0] => foo 123456
[1] => 23456
)
使用像
*?

<?php
$string = "foo 123456 bar"; // work with "foo 123456", "123456", etc.
if (preg_match("/.*?(\d{5,9}).*/", $string, $match)) {
    print_r($match);
};

有关更多信息:

由于您只需要数字,您只需从模式中删除
*

$string = "foo 123456";
if (preg_match("/\d{5,9}/", $string, $match)) {
    print_r($match);
};
请注意,如果输入字符串是
“123456789012”
,则代码将返回
123456789
(这是较长数字序列的子字符串)

如果您不想匹配作为较长数字序列一部分的数字序列,则必须添加一些环视:

preg_match("/(?<!\d)\d{5,9}(?!\d)/", $string, $match)

preg\u match(“/”)只需从您的模式中删除
*
。在两个preg\u match表达式中,前者都起作用,为了简洁起见,我选择了您的答案。我想排除任何长度超过9个字符的数字序列,但我无法使第二个表达式起作用。
preg_match("/(?<!\d)\d{5,9}(?!\d)/", $string, $match)