2013-05-16 105 views
0

我試圖返回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 
) 
+0

只要從你的模式中刪除'。*'。 – nhahtdh

回答

1

因爲只需要數字,你可以從模式中刪除.*

$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) 

DEMO

(?<!\d)會檢查數字序列前面沒有數字。 (?<!pattern)零寬度負向後視,這意味着如果不消耗文本,它會檢查從當前位置向後看的模式是否匹配。

(?!\d)檢查數字序列後沒有數字。 (?!pattern)零寬度負向預測,這意味着如果不消耗文本,它將檢查從當前位置向前看,沒有匹配的模式。

+0

在前兩種preg_match表達式中,前者都有效,爲簡潔起見,我選擇了你的答案。我想排除任何長度超過9個字符的數字,但我無法讓你的第二個表達式工作。 – varubi

+0

@Varubi:它應該工作。我已經添加了一個演示。 – nhahtdh

0

使用 「本地」 非貪婪像.*?

<?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