Php 从文本中提取4位数字
我想使用preg_match_all只提取四位数字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('/(
如果我想得到四位数还是两位数?(第二种情况)指定范围
{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);