tags:

views:

53

answers:

2

Sorry for the redundancy, I should've asked this in my previous question here: http://stackoverflow.com/questions/3061407/whats-the-regex-to-solve-this-problem

This question is an extension:

From the elements in an array below:

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

I'm separating out apps/{number}/ and apps/{number} using:

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

Now, how do I also push {number} to another array with the same regex?

+1  A: 

preg_match() takes an array as third parameter that will contain the matches. Create a capture group with () and the number will then be contained in $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] contains the whole matched pattern as described in the documentation. Of course you can name the array as you like.

Felix Kling
Works as expected.. thanks!
Yeti
A: 

If finding the URLs that match is the goal, you could use preg_grep() instead:

$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);
Latchezar Tzvetkoff