Reputation: 41
I'd like to use the preg_match function (procedural, not oop) to validate user provided urls for images hosted on imgur.com
The purpose is to include the called image into a php page (hotlink) where users can use the image as their avatar/profile image.
As far as I know, a valid imgur hotlink is:
https://i.imgur.com/FILENAME.XYZ
Where "FILENAME" is something like "2lcqfvJ" and "XYZ" is the image format like "jpg". Example:
https://i.sstatic.net/2UXVL.jpg
I've some difficulties to figure out the pattern for the validation. I use this method yet to identify valid tinypic and imageshack valid urls
I tried this to check the url provided by the user, but it seems to not work:
if ( !preg_match('/^(http|https):\/\/(.*?)\.(imgur)\.(com)\/.(png|jpg|gif|PNG|JPG|GIF)$/i',$url) )
Passing the url above (https://i.sstatic.net/2UXVL.jpg) the function doesn't recognize it as a valid imgur link. So I can imagine I've done something wrong with the regular expression.
Upvotes: 1
Views: 825
Reputation: 20440
(Posted answer on behalf of the question author).
The pattern below works:
!preg_match('/^(http|https):\/\/(.*?)\.(imgur)\.(com)\/(.*?)\.(png|jpg|gif|PNG|JPG|GIF)$/i',$url)
Upvotes: 1
Reputation: 91385
Your regex can be simplified:
!preg_match('~^https?://i\.imgur\.com/\w+\.(png|jpe?g|gif)$~i', $url)
Upvotes: 0