Regex Flickr Parser
Today’s Regex is used to parse a string for Flickr links and extract the Photo_ID. Once we have the Photo_ID we’re able to create a standard embed code from nearly any Flickr URL.
Supported Links:
The following Regex supports these Flickr links and embed code snippets.
Normal URL : http://www.flickr.com/photos/gambort/6501997531/ Short URL : http://flic.kr/p/aUyrkH Embed : >a href="http://www.flickr.com/photos/gambort/6501997531/" title="Skyrim black dragon by gambort, on Flickr"><img src="http://farm8.staticflickr.com/7004/6501997531_80aa9da91a.jpg" width="500" height="334" alt="Skyrim black dragon"></a> ****Short Code id needs to be decoded and replaced with the full photo ID****
Again, I’ve broken it up the Regex and commented each line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $regexstr = '~ # Match Flickr link and embed code (?:<a [^>]*href=")? # If a tag match up to first quote of src (?: # Group Flickr url https?:\/\/ # Either http or https (?:[\w]+\.)* # Optional subdomains (?: # Group host alternatives. flic\.kr # Either flic.kr | flickr\.com # or flickr.com ) # End Host Group (?:\/photos)? # Optional video sub directory \/[^\/]+\/ # Slash and stuff before Id ([0-9a-zA-Z]+) # $1: PHOTO_ID is numeric [^\s]* # Not a space ) # End group "? # Match end quote if part of src (?:.*></a>)? # Match the end of the a tag ~ix'; |
Usage Example:
This example is more involved than the previous posts because we need to make an API call to get the image URL after we get the Flickr Photo_ID. I’ve also included a Base58 decode function incase the url is the short flic.kr style link.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | function ParseForFlickr($string){ $regexstr = <<REGEX FROM ABOVE>>; require_once('phpFlickr.php'); $f = new phpFlickr("<<Flickr API Key>>"); preg_match_all($regexstr, $string, $matches, PREG_SET_ORDER); //Loop results foreach ($matches as $val) { //If short code decode it if (strpos($val[0], "flic.kr") !== false) { $val[1] = $this->flickrDecode($val[1]); } //make flickr api call with photo id $pinfo = $f->photos_getSizes($val[1]); //Array 3 is the medium 500 size $imgstr = ' <p><img class="upostimg" src="'.$pinfo[3]['source'].'" /></p> '; $string = str_replace($val[0],$imgstr,$string); } return $string; } function flickrDecode($num){ $alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; $decoded = 0; $multi = 1; while (strlen($num) > 0) { $digit = $num[strlen($num)-1]; $decoded += $multi * strpos($alphabet, $digit); $multi = $multi * strlen($alphabet); $num = substr($num, 0, -1); } return $decoded; } |
For more Regex see Regex YouTube Parser or Regex Vimeo Parser
Leave a Reply