tags:

views:

1274

answers:

2

i'm running out of ideas on the best regex implementation for this problem.

Sample user input:

bla bla bla http://foo.com bla bla bla http://tinypic.com/boo.png bla bla bla

Looking for solution that will detect non-image url and turn it into a link and also turn image url into an image embed (IMG tag).

so the output will be:

bla bla bla <a href="http://foo.com"&gt;http://foo.com&lt;/a&gt; bla bla bla <img src="http://tinypic.com/boo.png" /> bla bla bla

Related

+3  A: 

Break it into multiple steps.

First, find links with something like:

/http:[^ ,]+/i

Then replace the matched string with new content based on the type, which you can detect by matching the string to be replaced against something like:

/\.(jpg|png|gif|bmp)$/i
MarkusQ
+1  A: 

Looking for solution that will detect non-image url

There is no such thing as an image or non-image URL. The presence (or absence) of a ‘.gif’/‘.jpeg’/‘.jpg’/‘.png’ file extension has nothing to do with whether a URL points to an image or not.

eg. “http://www.example.com/getimage/3” could return a perfectly good JPEG. There is no way to know what media type a URL points to without fetching it (using GET or, better, HEAD) and checking the returned ‘Content-Type’ is ‘image/something’.

bobince