Doesn't matter how much I try, I can't figure this out.
I have a comments section on my website and I have some functions using regex expressions.
One of mine functions replaces URLs in the content string in links, as long as it can, it is working pretty well. But I wanted to check if the match is a normal link or if it is an image (ends with .jpg, .gif, etc) if so, it should then have the replace expression with <img>
tags.
What I have so for:
function url_parse($string) {
$string = preg_replace('/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is', '<a href="http$2://$3" target="_blank">$1$3</a>', $string);
return $string;
}
This one is the function to replace the links. Easy as that. But my idea to check if it is a image, I made alot of confusions here. I don't even know how to extact the link, so I do this:
function geturl($string) {
$regex = '/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is';
preg_match_all($regex, $string, $matches);
return ($matches[0]);
}
I even made a function to check if it is actually a link to a image
function isIMG($url){
$ext = strrpos( $url, ".");
if ($pos === false) {
return false;
}
$ext = strtolower(trim(substr( $url, $pos)));
$exts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif");
if (in_array($ext, $exts)) {
return true;
}
else {
return false;
}
}
But, I got myself into a LIMBO. I just can't put it all working together. I tried everything... Any help?
The objective here is:
Check if the URL extracted from the string is a normal link OR if it have an image ext.
preg_replace
in the string. I hope that this question doesn't seem messed up. Really needing any help here.