在文本块中单击链接的最佳方法

Sil*_*ght 22 php regex preg-replace

我想要:

Here is link: http://google.com
And http://example.com inside.
And another one at the very end: http://test.net
Run Code Online (Sandbox Code Playgroud)

成为:

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>
Run Code Online (Sandbox Code Playgroud)

看起来像一个简单的任务,但我找不到一个有效的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);
Run Code Online (Sandbox Code Playgroud)

Aka*_*run 51

使用此方法(适用于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);
}
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于不以http://开头的链接.我建议添加一个str_replace来寻找www.并添加http:// infront.然后我会为double htt p:// htt p://添加另一个str_replace checkign以将其替换为一个 (2认同)

Mar*_*aio 6

尝试这样的事情:

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

$result = make_links_clickable($text);
Run Code Online (Sandbox Code Playgroud)


Law*_*one 5

你应该参考这个答案用HTML链接替换文本中的URL


San*_*nex 5

function makeClickableLinks($text)
{
$text = html_entity_decode($text);
$text = " ".$text;
$text= preg_replace("/(^|[\n ])([\w]*?)([\w]*?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $text);  
$text= preg_replace("/(^|[\n ])([\w]*?)((www|wap)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text);
$text= preg_replace("/(^|[\n ])([\w]*?)((ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"$4://$3\" >$3</a>", $text);  
$text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text);  
$text= preg_replace("/(^|[\n ])(mailto:[a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"$2@$3\">$2@$3</a>", $text);  
$text= preg_replace("/(^|[\n ])(skype:[^ \,\"\t\n\r<]*)/i", "$1<a href=\"$2\">$2</a>", $text);  
        return $text;
}
Run Code Online (Sandbox Code Playgroud)

合作:

www.example.com

https://www.example.com

http://www.example.com

wap.example.com

ftp.example.com

user@example.com

SKYPE:例如

邮寄地址:user@example.com

atherprotocol://示例.com

  • 这些连续的更换浪潮根本无法解释。这个答案是不完整的,任何使用这个答案的人都可能是盲目复制粘贴的。这个答案应该编辑得更加慷慨/有教育意义。应该只有一个 `preg_replace()` 调用;应该有一个模式数组和一个替换数组。 (2认同)