我试图返回5到9位数字之间的一系列数字。我希望能够获得最长的匹配,但不幸的是,preg_match只是返回匹配的最后5个字符。preg_match返回最长匹配
$string = "foo 123456";
if (preg_match("/.*(\d{5,9}).*/", $string, $match)) {
print_r($match);
};
将产生结果
Array
(
[0] => foo 123456
[1] => 23456
)
我试图返回5到9位数字之间的一系列数字。我希望能够获得最长的匹配,但不幸的是,preg_match只是返回匹配的最后5个字符。preg_match返回最长匹配
$string = "foo 123456";
if (preg_match("/.*(\d{5,9}).*/", $string, $match)) {
print_r($match);
};
将产生结果
Array
(
[0] => foo 123456
[1] => 23456
)
因为只需要数字,你可以从模式中删除.*
:
$string = "foo 123456";
if (preg_match("/\d{5,9}/", $string, $match)) {
print_r($match);
};
注意,如果输入的字符串"123456789012"
,那么代码将返回123456789
(这是一个子更长的数字序列)。
如果你不想匹配数的序列号是一个较长序列的一部分,那么你必须添加一些环视:
preg_match("/(?<!\d)\d{5,9}(?!\d)/", $string, $match)
(?<!\d)
会检查数字序列前面没有数字。 (?<!pattern)
是零宽度负向后视,这意味着如果不消耗文本,它会检查从当前位置向后看的模式是否匹配。
(?!\d)
检查数字序列后没有数字。 (?!pattern)
是零宽度负向预测,这意味着如果不消耗文本,它将检查从当前位置向前看,没有匹配的模式。
使用 “本地” 非贪婪像.*?
<?php
$string = "foo 123456 bar"; // work with "foo 123456", "123456", etc.
if (preg_match("/.*?(\d{5,9}).*/", $string, $match)) {
print_r($match);
};
结果:
Array
(
[0] => foo 123456 bar
[1] => 123456
)
欲了解更多信息:http://en.wikipedia.org/wiki/Regular_expression#Lazy_quantification
只要从你的模式中删除'。*'。 – nhahtdh