-1

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.

Jake
  • 1,469
  • 4
  • 19
  • 40
  • an img just uses the if you link an image you would just do Can you elaborate more on what you already have in place? – cwhelms Jul 06 '11 at 18:59
  • Please share the code how you do it already for the normal link. – hakre Jul 06 '11 at 19:00
  • 2
    Blimey; I haven't seen `ereg_replace` in years! Is there any particular reason, @JakeAero, that you ignored that **massive red warning** on its manual page, stating that "this function has been DEPRECATED as of PHP 5.3.0", and that "relying on this feature is highly discouraged"? Or the long-standing tip at the bottom that reads "`preg_replace()`, which uses a Perl-compatible regular expression syntax, is often a faster alternative to `ereg_replace()`"? – Lightness Races in Orbit Jul 06 '11 at 19:03

2 Answers2

0

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Assuming you are using PHP, and the URL is stored in $url:

if (!preg_match("@^https?\:\/\/@", $url)
{
    $url = "http://$url";
}

if (preg_match("@\.(gif|jpe?g|png)$@", $url))
{
   echo '<img src="' . $url . '" />"';
}
else
{
   echo '<a href="' . $url . '" target="_blank">' . $url . </a>;
}

This is not an exact method, as some pictures may be served with the correct MIME type without bearing a gif, jpeg, jpg or png extension.

This is a far better method to check if a link refers to a picture, but it is time- and bandwith consuming. As such, it would be better to store the result in a database at the same time $url is, for later reuses:

if (!preg_match("@^https?\:\/\/@", $url)
{
    $url = "http://$url";
}

$headers = get_headers($url, 1);
$mime_type = isset($headers["Content-Type"])  ?  $headers["Content-Type"]  :  "";

if (preg_match("@\.(gif|jpe?g|png)$@", $url)  ||  preg_match("@^image\/@", $mime_type))
{
   $html = '<img src="' . $url . '" />"';
}
else
{
   $html = '<a href="' . $url . '" target="_blank">' . $url . '</a>';
}
Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49