user3526915
user3526915

Reputation: 35

Regex pattern to detect a link but not an image

I've been fooling around for a while with regex. A few days ago I started modifying a regex pattern I found some time ago. It detects all hyperlinks, my version should only detect hyperlinks and not images.

http://domain.com/someimage.jpg

shouldn't be detected. But it does detect an image partly. I don't how to solve this.

The original regex:

/(https?)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/\S*)?/i

Link to my version:

http://regexr.com/38rv9

Please help. Thanks!

Upvotes: 3

Views: 205

Answers (2)

I would accomplish this by making sure what is clicked by the user does NOT end with an image file extension. You mention you are using php; have ONE condition statement that matches your original regex:

/(https?)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/\S*)?/i

but does not match any common image file extension at the END of the expression:

/^.*\.*[*(jpg$|jpeg$|gif$|png$|tif$)]/i

This would work for any text string that precedes the image file extension; preg_match will be useful to accomplish this.

Upvotes: 0

el3ien
el3ien

Reputation: 5405

You just need a space at last.

/((https?)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/(?:(\S(?!jpg|jpeg|png|gif))*))?)\s/ig

Upvotes: 2

Related Questions