Senne Vandenputte
Senne Vandenputte

Reputation: 539

PHP - find and convert all links and images to display them in HTML

I have seen a lot of topics related to this but can't find something that's working for links AND images.

On my PHP page I echo $content, which contains a record from my DB. In this string, there can be urls and image urls. What I need is a function that automatically finds these urls and displays them in proper HTML. So normal links should be shown as <a ...>....</a> and image links (ending with jpeg, jpg, png, gif,...) should be shown as <img ...>.

This is what I found for the url website links only:

$content = preg_replace("~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
                        "<a href=\"\\0\">\\0</a>", 
                        $content);

echo $content; 

I think I should use some regex code for this but I'm not very familiar with that.Thanks a lot!

EDIT:

http://example.com, https://example.com should all be shown like <a href="url">url</a>. All urls that are not images;

http://www.example.com/image.png should be shown as <img src="http://www.example.com/image.png"> This goes for all urls ending with an image extension like png, jpeg, gif etc

Upvotes: 2

Views: 1236

Answers (1)

Jan
Jan

Reputation: 43199

One way to have both your items (images and links) transformed, would be to apply the more specific pattern first and then use a negative lookbehind on src=' in the other ones:

<?php
$content = "I am an image (http://example.com/image.png) and here's another one: https://www.google.com/image1.gif. I want to be transformed to a proper link: http://www.google.com";

$regex_images = '~https?://\S+?(?:png|gif|jpe?g)~';
$regex_links = '~
                (?<!src=\') # negative lookbehind (no src=\' allowed!)
                https?://   # http:// or https://
                \S+         # anything not a whitespace
                \b          # a word boundary
                ~x';        # verbose modifier for these explanations

$content = preg_replace($regex_images, "<img src='\\0'>", $content);
$content = preg_replace($regex_links, "<a href='\\0'>\\0</a>", $content);
echo $content;
# I am an image (<img src='http://example.com/image.png'>) and here's another one: <img src='https://www.google.com/image1.gif'>. I want to be transformed to a proper link: <a href='http://www.google.com'>http://www.google.com</a>
?>

See a demo on ideone.com

Upvotes: 1

Related Questions