Search code examples
phpimagehyperlinkpreg-replaceereg

Link or image preg/ereg replace?


Heres my issue. I'm building a website where you can share links/pictures. Now heres what I want to do. If the link is a link to a site, then display a link such as:

<a href="http://example.com" target="_blank">http://example.com</a>

But heres my downfall, if it a picture(jpg, gif, png, ect) I want to display that on the page instead of the link. How do I go about doing that?

-- Forgot to add:

$profile_post_post = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\" target=\"_blank\">\\0</a>", $profile_post_post);

Thats the code that makes the link.


Solution

  • Use preg_replace_callback, providing a callback that selects the link contents conditionally based on its format. i.e. if it ends in .jpg, render an img tag. If it ends in anything other than a typical image file extension, print its name.