求一段正则 链接

2013-01-16 11:01:11 +08:00
 liuyao729
把 字符串中没有加链接的 url 加上链接 有的就不用了。
$str = '<a href="xxxx">xsx</a> http://www.v2ex.com ';
显示成
<a href="xxxx">xsx</a> <a href="http://www.v2ex.com">http://www.v2ex.com</a>
3175 次点击
所在节点    程序员
9 条回复
jeffrey
2013-01-16 13:03:25 +08:00
mozillazg
2013-01-16 13:40:11 +08:00
个人觉得求正则的话,提问者应该至少说明三件事:
* 使用的程序语言或工具
* 待处理字符串特征及示例
* 结果字符串的细节约束
上面几点不讲清楚的话,回答者会搞不清楚提问者的具体需求,提问者也得不到想要的正则。
mozillazg
2013-01-16 13:45:31 +08:00
[^"']https?://\S+
clowwindy
2013-01-16 13:57:02 +08:00
liuyao729
2013-01-17 06:49:14 +08:00
mozillazg
2013-01-17 09:11:13 +08:00
@liuyao729 首先声明,我不会 PHP 也没有测试环境,只是上网查了一下 PHP 的替换函数。
用了一个在线执行 PHP 代码的网站进行的测试(PHP5),
该正则比较简陋并且对 <a href="http://xx?q=http://"></a> 会误判:
$text = 'http://abc<a href="http://xxx">xsx</a> http://v2ex.com https://abc<img />abd';
print preg_replace('%(?<!"|\')https?://[^\s<]+%', '<a href="$0">$0</a>', $text);
//<a href="http://abc">http://abc</a><a href="http://xxx">xsx</a> <a href="http://v2ex.com">http://v2ex.com</a> <a href="https://abc">https://abc</a><img />abd
mozillazg
2013-01-17 09:23:29 +08:00
ljbha007
2013-01-17 10:17:15 +08:00
正则: (https*:\/\/\w+\.\w+.\(?:\.\w+)*)
替换:<a href="$1">$1</a>

PHP的preg和javascript通用
liuyao729
2013-01-18 02:54:29 +08:00
从目前看来没有好的解决办法了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/57747

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX