正则表达式从Flickr照片URL获取ID?

时间:2015-08-27 15:26:21

标签: php regex

所以我正在尝试在PHP中创建一个正则表达式,以从其URL中获取照片的ID。

这些是潜在的模式:

https://www.flickr.com/photos/12037949754@N01/
        www.flickr.com/photos/12037949754@N01/
            flickr.com/photos/12037949754@N01/
https://www.flickr.com/photos/user/12341234123
        www.flickr.com/photos/user/12341234123
            flickr.com/photos/user/12341234123

我猜我使用的是preg_match,所以类似于:

if (preg_match("regex", $url, $matches)) {
    return "flickr photo id:" . $matches[x];
}

但是我不确定如何创建这个正则表达式,以便它可以在每种情况下返回ID,因此它在$matches中的位置每次都是相同的。

有什么想法吗?我好好看看正则表达式,但没有运气!

3 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式捕获每个网址的照片ID:

$regex = '~(?<=/)\d+(?:@\w+)?(?=/|$)~';

RegEx Demo

RegEx分手:

(?<=/)     # Positive Lookbehind to make sure / is previous character
\d+        # match 1 or more digits
(?:@\w+)?  # match optional @ followed by a 1 or more word characters
(?=/|$)    # Positive Lookahead to make sure next character is / or end of line

答案 1 :(得分:1)

if (preg_match("/([0-9]+[\\@a-zA-Z0-9]+)/",$url,$matches)){
    return $matches[0];
}

示例:http://www.regexr.com/3blts

如果您不想要@N01,那么只需:

if (preg_match("/([0-9]+)/",$url,$matches)){
    return $matches[0];
}

答案 2 :(得分:1)

您可以使用此正则表达式来提取ID:

/(?:https?:\/\/)?(?:www\.)?flickr\.com\/photos\/(?:user\/)?(\d+)/

演示:https://regex101.com/r/jQ5eK3/1

因此,使协议可选,www子域可选,user/可选。然后只捕获找到的数字。

PHP演示:https://eval.in/423621

PHP用法:

$regex = '/(?:https?:\/\/)?(?:www\.)?flickr\.com\/photos\/(?:user\/)?(\d+)/';
$url = 'https://www.flickr.com/photos/user/12341234123';
if (preg_match($regex, $url, $matches)) {
print_r($matches);
}