Search code examples
phpregexhyperlinkpreg-replacepreg-match

Converting links to hyperlinks but the first link convert all the others


I have a small form which allows users to send a description for an item, i'd like to convert every links to hyperlinks but I have an issue with my code, when it finds the first link, it converts every other hyperlinks with the same link. So this code works when the text input contains one link but as soon as it contains 2 or more, the issue pops up!

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

if(preg_match($reg_exUrl, $_POST['description'], $url))
{
   $_POST['description'] = preg_replace($reg_exUrl, '<a target="_blank" href="'.$url[0].'">'.$url[0].'</a>', $_POST['description']);
}

Example - 1 link:

Text input: "blablabla http://google.com"
Result: "blablabla <a href="http://google.com">http://google.com</a>"

Example - 2 links:

Text input: "blablabla http://google.com
blablabla http://youtube.com"
Result: "blablabla <a href="http://google.com">http://google.com</a>
blablabla <a href="http://google.com">http://google.com</a>"

I hope I was clear enough, if you have any idea on how to solve this issue, that'd be awesome!

Thanks


Solution

  • Try

    function makeClickableLinks($s)
    {
        return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $s);
    }
    

    Calling function

    echo makeClickableLinks($_POST['description']);