2012-12-08 17 views
1

下面是一個例子字符串:得到一個預定義的結構數組或preg_match_all

「從12人的60條評論中,20%的用戶」 (我們稱之爲V $)

我一直在使用preg_match_all得到一個陣列的所有號碼

$pattern = '!\d+!'; 
preg_match_all($pattern, $v, $matches, PREG_SET_ORDER); 

結果我得到的是:

Array 
(
    [0] => Array 
     (
      [0] => 60 
     ) 
    [1] => Array 
     (
      [0] => 12 
     ) 
    [2] => Array 
     (
      [0] => 20 
     ) 
) 

但儘管嘗試了一段時間,我一直無法得到我想要的。 我想是這樣的:

Array 
(
    [0] => 60 
    [1] => 12 
    [2] => 20 
) 

也許我應該使用的preg_match呢?但與preg_match我只能得到一個值...或者也許隨着一個循環?它看起來像一個醜陋的黑客...應該有一種專業的方式...在此先感謝PHP專家! ;)

+0

刪除 「PREG_SET_ORDER」,會讓你幾乎得到你想要的。 $ matches [0]將會是你的數組。 –

回答

0

。假定格式始終保持不變,你可以做到以下幾點:

<?php 

    // Input string/line 
    $v = "60 reviews from 12 people, 20% of users"; 

    // Match regex (0-9; min 1 or max unlimited numbers) 
    preg_match_all("/[0-9]{1,}/", $v, $matches); 

    // Remove/sub key 
    $matches = $matches[0]; 

    // Echo out 
    print_r($matches); 

?> 

這將輸出:

Array ( 
     [0] => 60  // < Access using $matches[0] 
     [1] => 12  // < Access using $matches[1] 
     [2] => 20  // < Access using $matches[2] 
) 
+0

謝謝,我認爲它的工作,但恐怕格式會改變,永遠不會相同 – Julien

+0

不客氣。然後及時,如果不保持相同或格式更改,則需要更復雜的正則表達式來處理「評論」,「人員」和「用戶」。這不是一個複雜的正則表達式! :) – nickhar

相關問題