Domanda

I have searched this website on how to extract facebook id from url that starts from photo.php?fbid= but i have a long url and know how to get photo id

Example1 : photo.php?fbid=10151987845617397 (the complete url is stored in the $url variable which is checked using preg_match i believe)

!preg_match("|^http(s)?://(www.)?facebook.com/photo.php(.*)?$|i", $url) || !$pid

the above code fetches facebook id 10151987845617397 and puts it in the variable $pid.

If I have a long url, how can i change the code? Here is the url Example2 : https://www.facebook.com/nokia/photos/a.338008237396.161268.36922302396/10151987845617397/?type=1&theater In the above url 10151987845617397 is the photo id that i need to capture and put it in variable $pid.

what changes do i need to do in the preg_match string?

In other words to get the photoid 10151987845617397 as output in the $pid variable:

For url facebookcom/photo.php?fbid=10151987845617397 The syntax is !preg_match("|^http(s)?://(www.)?facebook.com/photo.php(.*)?$|i", $url) || !$pid

So for url facebookcom/nokia/photos/a.338008237396.161268.36922302396/10151987845617397/?type=1&theater What would be the syntax

Please help Thanks

È stato utile?

Soluzione

The simple solution and quite readable: Use the entire string as a regex, use () around what you want to match:

// $tmp[1] = www or nothing
// $tmp[2] = "user" (i.e nokia)
// $tmp[3] = album id?
// $tmp[4] = photos
// $tmp[5] = Long url as requested
function extract_id_from_album_url($url) {
    preg_match('/https?:\/\/(www.)?facebook\.com\/([a-zA-Z0-9_\- ]*)\/([a-zA-Z0-9_\- ]*)\/([a-zA-Z0-9_\.\-]*)\/([a-zA-Z0-9_\-]*)(\/\?type=1&theater\/)?/i', $url, $tmp);

    return isset($tmp[5]) ? $tmp[5] : false;
}

Backslashes are needed to ensure the . is seen as a literal (and not regex syntax). Questionmarks to allow optional urls. Using more regex syntax can make the matching "query" much shorter and extendable, but also makes it harder to read.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top