Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.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 从文本中提取4位数字_Php_Regex_Preg Match - Fatal编程技术网

Php 从文本中提取4位数字

Php 从文本中提取4位数字,php,regex,preg-match,Php,Regex,Preg Match,我想使用preg_match_all只提取四位数字 如果我想得到四位数还是两位数?(第二种情况)指定范围{4}如下: preg_match_all('/([\d]+)/', $text, $matches); foreach($matches as $match) { if(length($match) == 4){ return $match; } } 对于两位数: preg_match_all('/(

我想使用preg_match_all只提取四位数字


如果我想得到四位数还是两位数?(第二种情况)

指定范围
{4}
如下:

    preg_match_all('/([\d]+)/', $text, $matches);

    foreach($matches as $match)
    {
        if(length($match) == 4){
            return $match;
        }
    }
对于两位数:

preg_match_all('/(\d{4})/', $text, $matches);
使用

顺便说一句,如果只有
\d
要匹配,则无需使用字符类(我省略了方括号)

如果要匹配4位或2位数字,请使用

preg_match_all('/(\d{4})/', $text, $matches);
return $matches;

preg\u match\u all('/(?要匹配所有
4
数字,您可以使用regex
\d{4}

preg_match_all('/(?<!\d)(\d{4}|\d{2})(?!\d)/', $text, $matches);
return $matches;
在匹配
2
4
数字的旁边,可以使用正则表达式
\d{2}\d{4}
或更短的正则表达式
\d{2}(\d{2})


@BoltClock:在看到您的评论之前更新:)
preg_match_all('/(?<!\d)(\d{4}|\d{2})(?!\d)/', $text, $matches);
return $matches;
preg_match_all('/\b(\d{4})\b/', $text, $matches);
preg_match_all('/\b(\d{2}(\d{2})?)\b/', $text, $matches);