2010-06-17 65 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);