如何包裹<a href=""> all URL occurrence in my query</a>

时间:2013-10-19 14:34:34

标签: php regex

好吧,我认为我的问题的解决方案是使用REGEX,但我目前对它的了解阻碍了我实现我想要的结果。

所以基本上,如何在我的帖子/文本条目中出现所有URL以在查询时包含在<a href>元素中。

当来自数据库的echo $content;时,它将显示为:

this is a link http://somerandomsite.com, check it out!

但是如何在显示时将文本中的链接包含在<a href>标记中。

老实说,我不知道如何正确编写语法。但这就是我想出来的。

//get url from content
$link = strstr($content, 'http://');

//insert <a href> for all $link inside $content
//then display $content with all links wrapped in <href>

1 个答案:

答案 0 :(得分:0)

$a = 'this is a link http://somerandomsite.com, check it out!';

$a = preg_replace("/\b((?:http\:\/\/)|(?:www\.))([^ ,]+)/", "<a href=\"$1$2\">$1$2</a>", $a);

echo $a;