preg_match_all('/([\d]+)/', $text, $matches);
foreach($matches as $match)
{
if(length($match) == 4){
return $match;
}
}
我想使用 preg_match_all 函数提取仅包含四位数字的内容?
如果我想获取两位或四位数字,应该怎么做?(第二种情况)
preg_match_all('/([\d]+)/', $text, $matches);
foreach($matches as $match)
{
if(length($match) == 4){
return $match;
}
}
我想使用 preg_match_all 函数提取仅包含四位数字的内容?
如果我想获取两位或四位数字,应该怎么做?(第二种情况)
preg_match_all('/(\d{4})/', $text, $matches);
return $matches;
顺便提一下,如果你只需要匹配\d
,那么就不需要使用字符类(中括号可以省略)。
如果你想匹配4位数或2位数,可以使用以下正则表达式:
preg_match_all('/(?<!\d)(\d{4}|\d{2})(?!\d)/', $text, $matches);
return $matches;
我在这里使用负回顾 (?<!\d)
和负预查 (?!\d)
来防止匹配三位数的两位数字部分(例如,防止将 123
匹配为 12
)。
要匹配所有的4位数字,可以使用正则表达式\d{4}
preg_match_all('/\b(\d{4})\b/', $text, $matches);
如果想匹配两位数或四位数,可以使用正则表达式 \d{2}|\d{4}
或更短的正则表达式 \d{2}(\d{2})?
preg_match_all('/\b(\d{2}(\d{2})?)\b/', $text, $matches);
像这样指定范围{4}
:
preg_match_all('/(\d{4})/', $text, $matches);
对于两位数:
preg_match_all('/(\d{2})/', $text, $matches);