PHP将所有网址转换为html链接 [英] PHP Convert all urls into html links

查看:118
本文介绍了PHP将所有网址转换为html链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
用HTML链接替换文本中的URL

Possible Duplicate:
Replace URLs in text with HTML links

我通过下面的函数传递包含多个URL的字符串变量,以仅通过正确的HTML链接获得相同的内容.

I'm passing the string variable which contains multiple urls, through function below to get same thing only with proper HTML links.

public function convertUrlsToLinks($text){
    return preg_replace( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank">\0</a>', $text );
}

它根本不起作用.我想念什么?

It doesn't work at all. What am I missing?

代码必须跳过现有链接,<img>src值(或类似值).

Code must skip existing links, <img>'s src values (or something like that.)

推荐答案

假定您已经有一个html文档,那么我将URL的识别限制为

assuming you already have an html document, I limited the recognition of URLs to

  • 不是以"
  • 开头
  • 以http或www开头

我想出了这样的解决方案:

i came up with a solution like this:

$string = 'lorem ipsum www.foo.bar dolor sit <a href="http://fail.org">http://fail.org</a><img src="www.foo.bar"> amet http://abc.de.fg.com?bar=baz';
$rx = '%[^"](?P<link>(?:https?://|www\.)(?:[-_a-z0-9]+\.)+(?:[a-z]{2,4}|museum/?)(?:[-_a-z0-9/]+)?(?:\?[-_a-z0-9+\%=&]+)?(?!</a)(\W|$))%ui';
echo preg_replace_callback($rx, function($matches) {
    return '<a href="'.$matches['link'].'">'.$matches['link'].'</a>';
}, $string).PHP_EOL;

输出字符串是

lorem ipsum<a href="www.foo.bar ">www.foo.bar </a>dolor sit <a href="http://fail.org">http://fail.org</a><img src="www.foo.bar"> amet<a href="http://abc.de.fg.com?bar=baz">http://abc.de.fg.com?bar=baz</a>

正则表达式应该可以用作意向书,您的示例字符串可能会有所帮助

The regex should work as intendet, an example string of yours could help

这篇关于PHP将所有网址转换为html链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆