本文介绍了即使没有协议,也可以将网址从文本转换为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说$ content是文本区域的内容

Lets say that $content is the content of a textarea

/*Convert the http/https to link */
     $content = preg_replace('!((https://|http://)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="$1">$1</a> ', nl2br($_POST['helpcontent'])." ");
/*Convert the www. to link prepending http://*/
     $content = preg_replace('!((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$1">$1</a> ', $content." ");

这对于链接来说还可以,但是意识到当图像在文本中时,它破坏了标记...

This was working ok for links, but realised that it was breaking the markup when an image is within the text...

我现在正在尝试这样:

$content = preg_replace('!\s((https?://|http://)+[a-z0-9_./?=&-]+)!i', ' <a href="$1">$1</a> ', nl2br($_POST['content'])." ");
$content = preg_replace('!((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$1">$1</a> ', $content." ");

图像也受到尊重,但是问题在于,现在不会转换具有http://或https://格式的url..:

As is the images are respected, but the problem is that url's with http:// or https:// format won't be converted now..:

www.google.com->转换得很好

www.google.com -> Well Converted

http://google.com ->未转换(意外)

https://google.com ->未转换(意外)

我想念什么?

-编辑-

当前几乎可行的解决方案:

Current almost working solution:

$content = preg_replace('!(\s|^)((https?://)+[a-z0-9_./?=&-]+)!i', ' <a href="$2" target="_blank">$2</a> ', nl2br($_POST['content'])." ");
$content = preg_replace('!(\s|^)((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$2"  target="_blank">$2</a> ', $content." ");

这里的事情是,如果这是输入:

The thing here is that if this is the input:

我想要的所有网址(除name.domain之外的所有网址)均按预期进行了转换,但这是输出

All the urls I want (all, except name.domain) are converted as expected, but this is the output

请注意;插入,知道为什么吗?

Note an ; is inserted, any idea why?

推荐答案

尝试一下:

preg_replace('!(\s|^)((https?://|www\.)+[a-z0-9_./?=&-]+)!i', ' <a href="$2">$2</a> ',$text);

它将获取以http://或www开头的链接.

It will pick up links beginning with http:// or with www.

示例

这篇关于即使没有协议,也可以将网址从文本转换为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 03:18