0
votes

I am working on some code and I've done enough work to get something going. I want to replace a image url(s) and web links within that body of text.

E.G "This is my text with http://www.google.com and some image http://www.somewebimage.png"

Replace to "This is my text with <a href="http://www.google.com">http://www.google.com</a> and some image <img src="http://www.somewebimage.png">"

My hack gets me to replace the url(s) or the img links but not both..one is over written because of the order

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/';
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png";

if(preg_match($reg_exImg, $post, $img)) {
    $img_post =  preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post);
} else {
    $img_post = $post;
}
if(preg_match($reg_exUrl, $post, $url)) {
    $img_post =  preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post);
} else {
    $img_post = $post;
}

If I block the $reg_exUrl code block I get the image link if it runs the I get the url link.

1
What i'm trying to do is a simple feed where urls are links and img urls are embedded.. - Fabian Glace
First thing, testing a pattern with preg_match before using it with preg_replace is useless. - Casimir et Hippolyte
You should use a single pattern for the two cases, and then choose the replacement mask using preg_replace_callback. This way all is done in a single pass and nothing is overwritten. In the callback function you can use parse_url and explode to easily extract the file extension. - Casimir et Hippolyte

1 Answers

0
votes

You can do it in a single pass, your two patterns are very similar and it's easy to build a pattern that handles the two cases. Using preg_replace_callback, you can choose the replacement string in the callback function:

$post = "This is my text with http://www.google.com and some image http://www.domain.com/somewebimage.png";

# the pattern is very basic and can be improved to handle more complicated URLs
$pattern = '~\b(?:ht|f)tps?://[a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?~i';
$imgExt = ['.png', '.gif', '.jpg', '.jpeg'];
$callback = function ($m) use ($imgExt) {
    if ( false === $extension = parse_url($m[0], PHP_URL_PATH) )
        return $m[0];

    $extension = strtolower(strrchr($extension, '.'));

    if ( in_array($extension, $imgExt) )
        return '<img src="' . $m[0] . '" width="300" style="float: right;">';
    # better to do that via a css rule --^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    return '<a href="' . $m[0] . '" target="_blank">' . $m[0] . '</a>'; 
};

$result = preg_replace_callback($pattern, $callback, $post);