[英]Extract 4 digit number from a text
preg_match_all('/([\d]+)/', $text, $matches);
foreach($matches as $match)
{
if(length($match) == 4){
return $match;
}
}
i want use preg_match_all to extract only four digit number? 我想用preg_match_all只提取四位数?
and if i want to get four digit or two digit number? 如果我想得到四位数或两位数? (second case) (第二种情况)
Use 采用
preg_match_all('/(\d{4})/', $text, $matches);
return $matches;
No need to use a character class if you only have \\d
to match, by the way (I omitted the square braces). 顺便说一句,如果你只有\\d
匹配,则不需要使用字符类(我省略了方括号)。
If you want to match either 4-digit or 2-digit numbers, use 如果要匹配4位或2位数字,请使用
preg_match_all('/(?<!\d)(\d{4}|\d{2})(?!\d)/', $text, $matches);
return $matches;
Here I employ negative lookbehind (?<!\\d)
and negative lookahead (?!\\d)
to prevent matching 2-digit parts of 3-digit numbers (eg prevent matching 123
as 12
). 在这里,我使用负向lookbehind (?<!\\d)
和负向前导(?!\\d)
来防止匹配3位数字的2位数部分(例如,防止匹配123
为12
)。
To match all the 4
digit number you can use the regex \\d{4}
要匹配所有4
位数字,您可以使用正则表达式\\d{4}
preg_match_all('/\b(\d{4})\b/', $text, $matches);
Next to match either 2
or 4
digit number you can use the regex \\d{2}|\\d{4}
or a shorter regex \\d{2}(\\d{2})?
接下来匹配2
或4
位数字,您可以使用正则表达式\\d{2}|\\d{4}
或更短的正则表达式\\d{2}(\\d{2})?
preg_match_all('/\b(\d{2}(\d{2})?)\b/', $text, $matches);
Specify range {4}
like this: 像这样指定范围{4}
:
preg_match_all('/(\d{4})/', $text, $matches);
For two digits: 两位数:
preg_match_all('/(\d{2})/', $text, $matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.