2010-06-17 64 views
0

很抱歉的冗餘,我問過這在我以前的問題在這裏:What's the regex to solve this problem?Regex修復此問題? [延伸]

這個問題是一個擴展:

從元件在以下的數組:

http://example.com/apps/1235554/ 
http://example.com/apps/apple/ 
http://example.com/apps/126734 
http://example.com/images/a.jpg 

我分離出apps/{number}/apps/{number}使用:

foreach ($urls as $url) 
{ 
    if (preg_match('~apps/[0-9]+(/|$)~', $url)) echo $url; 
} 

現在,我怎樣才能將{number}推到另一個具有相同正則表達式的數組?

回答

1

preg_match()將數組作爲包含匹配的第三個參數。與()創建捕獲組,然後數字將被包含在$matches[1]

$numbers = array(); 

foreach ($urls as $url) 
{ 
    $matches = array(); 
    if (preg_match('~apps/([0-9]+)~', $url, $matches)) { // note the "()" in the regex 
     echo $url; 
     $numbers[] = $matches[1]; 
    } 
} 

FYI,$matches[0]包含如文檔中所述的整個匹配的模式。當然你可以根據你的喜好命名這個數組。

+0

按預期工作..謝謝! – Yeti 2010-06-17 13:16:09

0

如果發現匹配爲目標的網址,你可以使用preg_grep()來代替:

$urls = array(
    'http://example.com/apps/1235554/', 
    'http://example.com/apps/apple/', 
    'http://example.com/apps/126734', 
    'http://example.com/images/a.jpg', 
); 

$urls = preg_grep('!apps/(\d+)/?$!', $urls); 
print_r($urls);