9

Say i have a string of text such as

$text = "Hello world, be sure to visit http://whatever.com today";

how can i (probably using regex) insert the anchor tags for the link (showing the link itself as the link text) ?

mrpatg
  • 10,001
  • 42
  • 110
  • 169

2 Answers2

24

You can use regexp to do this:

$html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
  • your answer worked like a charm but if i wanna check also presence of www how would i do it? – Sarah Nov 29 '10 at 14:27
  • @Sarah unless you want to specifically target all url containing only www, this should catch those. If you need to check for www, then just add www\. like so: `\b(http://www\.\S+)` and that should catch only URL with www. – mason81 Jun 12 '13 at 20:13
  • If the document contains non-ascii characters (like asian languages), you can replace the "\S+" for: "[0-9a-zA-Z-._~:/?#\[\]@!$&'()*+,;=]+" if the URLs are only ascii characters (othewise don't change it) – lepe May 07 '14 at 09:18
  • To include https:// too: - $html_links = preg_replace('"\b(http\S+)"', 'Link', $text); – Mike Thrussell Mar 16 '15 at 13:31
5

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

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

pas-calc
  • 115
  • 9
Erwan
  • 2,512
  • 1
  • 24
  • 17