Reputation: 1023
I would like to make posted hyperlinks of images into embeded images on an html page. So, I'm working on setting up some regex syntax but am having difficulty and am hoping someone might be able to help.
I would like to turn, for example;
http://www.example.com/images/some_directory/logo.png
into
<img src='http://www.example.com/images/some_directory/logo.png'>
So, I would like to be able to do this for all typical image types. So far, I've cobbled together this but can't figure out how to finish the syntax.
<?php
$pic = 'http://www.example.com/images/some_directory/logo.png';
function post_image($pic)
{
return preg_replace('!((http(s)?://)[-a-z]+)!', '<img src="$1">', $pic);
}
$pic = post_image($pic);
echo $pic;
Upvotes: 0
Views: 109
Reputation: 1223
It might be easier just to use a preg_match and then build the <img src...
string around it your url, if it was correct - something like this?
<?php
$pic = 'https://example.com/i/like/aardvarks.gif';
function post_image($pic)
{
$pattern = '^(?:http|https).*(?:\.jpg|\.jpeg|\.png|\.gif)$';
if (preg_match($pattern, $pic))
return '<img src="{$pic}">';
else
return $pic;
}
$pic = post_image($pic);
echo $pic;
You'll probably want to add the i-modifier (same for javascript and php, so this guide will work fine) to the end of the regex as well, to ignore case (since you might get JPEG, jPEG, JPG, gIf and all kinds of funny variations).
Upvotes: 0
Reputation: 71538
You could perhaps try a regex like this:
'!((?:https?://)?[-a-z_/.]+\.(?:png|jpg|bmp|gif))!i'
I put the extentions of png
, jpg
, bmp
and gif
; you can add more if you want to.
Upvotes: 1