replace any url's within a string of text, to clickable links with php

You can use regexp to do this:

$html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);

I write this function. It replaces all the links in a string. Links can be in the following formats :

  • www.example.com
  • http://example.com
  • https://example.com
  • example.fr

The second argument is the target for the link ('_blank', '_top'... can be set to false). Hope it helps...

public static function makeLinks($str, $target='_blank')
{
    if ($target)
    {
        $target = ' target="'.$target.'"';
    }
    else
    {
        $target = '';
    }
    // find and replace link
    $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.~]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str);
    // add "http://" if not set
    $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
    return $str;
}

Edit: Added tilde to make urls work better https://regexr.com/5m16v

Tags:

Php

Regex