Sorry for the redundancy, I should've asked this in my previous question here: What's 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}
us开发者_如何转开发ing:
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?
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.
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);
精彩评论