使链接在文本块中可单击的最佳方式

2022-08-30 18:51:04

我想要:

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

成为:

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>

这似乎是一个微不足道的任务,但我找不到一个有效的PHP函数。你有什么想法吗?

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);

答案 1

使用这个(适用于ftp,http,ftps和https方案):

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

答案 2

试试下面这样:

function make_links_clickable($text)
{
   return preg_replace ('/http:\/\/[^\s]+/i', "<a href=\"${0}\">${0}</a>", $text);
} 

$result = make_links_clickable($text);

推荐