Best way to make links clickable in block of text

Silver Light picture Silver Light · Mar 17, 2011 · Viewed 31.1k times · Source

I want:

Here is link: http://google.com
And http://example.com inside.
And another one at the very end: http://test.net

to become:

Here is link: <a href="http://google.com">http://google.com</a>
And <a href="http://example.com">http://example.com</a> inside.
And another one at the very end: <a href="http://test.net">http://test.net</a>

Seems like a trivial task, but I cannot find a PHP function that works. Do you have any ideas?

function make_links_clickable($text){
    // ???
}

$text = 'Here is link: http://google.com
And http://example.com inside.
And another one at the very end: http://test.net';

echo make_links_clickable($text);

Answer

Akarun picture Akarun · Mar 17, 2011

Use this (works with ftp, http, ftps and https schemes):

function make_links_clickable($text){
    return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);
}