我正试图找到一个只有8个数字的数字,这是我已经拥有的代码:
preg_match_all("/([0-9]{8})/", $string, $match)
但这会从长于8位的数字串中提取8个数字
如有任何帮助,将不胜感激
感谢
我将使用'd
而不是[0-9]
如果您的字符串只包含一个八位数
使用^
和$
分别匹配字符串的开始和结束:
preg_match_all('/^('d{8})$/', $string, $match)
如果在一个较大的字符串中,您匹配的数字最多应为八位
快速但略显野蛮的方法:
使用'D
([^0-9]
(匹配"非数字":
preg_match_all('/^|'D('d{8})'D|$/', $string, $match)
Lookbehinds/lookahead可能会让情况变得更好:
preg_match_all('/(?<!'d)('d{8})(?!'d)/', $string, $match)
您需要单词边界
/'b[0-9]{8}'b/
示例:
$string = '34523452345 2352345234 13452345 45357567567567 24573257 35672456';
preg_match_all("/'b[0-9]{8}'b/", $string, $match);
print_r($match);
输出:
Array
(
[0] => Array
(
[0] => 13452345
[1] => 24573257
[2] => 35672456
)
)
这可能比其他两个建议更好:
preg_match_all('/(?<!'d)('d{8})(?!'d)/', $string, $match)
注意,'d
等同于[0-9]
。
preg_match_all("/(?:^|'D)('d{8})(?:'D|$)/", $string, $match);
起始和结束不匹配的组(?:(允许字符串的任何非数字(''D(或起始(^(或结束($(。
可能包含除数字之前和之后的任何内容。
preg_match_all("/[^'d](['d]{8})[^'d]/", $string, $match)