2012-07-21 100 views
1

我想加載一個遠程網站並獲取括號內的所有數字。但是最終發生的是它只與最後一個值相匹配。PHP preg_match_all括號中的數字

我的正則表達式是否錯誤?我使用正確的標誌嗎?

我已經添加了它應該在第二個$ html變量中匹配的示例。

//$html = file_get_contents("http://example.com/test.html"); 

    $html = "(1234) (12) (1) \r\n (1346326)"; 
    preg_match_all("^[(\d)]+$^", $html, $matches, PREG_PATTERN_ORDER); 
    print_r($matches); 
    echo "<br>"; 
    foreach ($matches as $val) { 
     echo "matched: " . $val[0] . "\n"; 

    } 

謝謝。

回答

4

如何:

preg_match_all("/\((\d+)\)/", $html, $matches, PREG_PATTERN_ORDER); 
print_r($matches[1]); 
+0

謝謝這個工作。我必須調整這個foreach 'code' \t \t $ html =「(1234)(12)(1)\ r \ n(1346326)」; preg_match_all(「/ \((\ d +)\)/」,$ html,$ matches,PREG_PATTERN_ORDER); \t \t print_r($ matches [1]); \t \t \t \t echo「
」; \t \t foreach($ matches [1] as $ val){ \t \t echo「matched:」。 $ val。 「
\ n」; \t \t}'code' – 2012-07-21 15:55:29

0

我看到了兩個可能的問題。

首先,您從匹配的開始(^)到結束($),它只會匹配恰好在行首和行尾之間的內容。

其次,您很可能希望使用/ GS正則表達式參數設置爲啜這一切。

preg_match_all("/\b(\d+)\b/gs" ... 
+0

在PHP中沒有「g」修飾符。 'preg_match_all()'總是全局的。 – ridgerunner 2012-07-21 15:38:01