使用PHP将http://添加到文本主体中检测到的URL中


Adding the http:// to a detected URL in a body of text with PHP

在插入数据库之前,我使用以下命令自动向注释中检测到的任何URL添加标记。

$pattern = "@'b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+'@)?(([0-9]{1,3}'.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+'.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]'.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:'@&=+$,%#-]+)*/?)@";
$text_with_hyperlink = stripslashes(preg_replace($pattern, '<a href="'0" class="oembed">'0</a>', $body));

除了我希望任何键入的没有"http://"的URL都能添加到URL的开头之外,一切都很好。

例如

上面的代码包含一条评论,其中包含"来访问我们的网站"http://www.facebook.com'

返回come visit our site <a href="http://www.facebook.com">http://www.facebook.com</a>

然而,如果用户键入"来访问我们的网站www.facebook.com"

我希望它返回带有http://前缀的url。

我该如何修改我的代码以产生这种检测?

编辑:我很抱歉没有提到最初的解决方案也应该能够检测非www.域名,如m.facebook或facebook.com理想情况下。

一个快速而肮脏的解决方案是用http://www.?替换www.?,如下所示:

$text_with_hyperlink = preg_replace("|(?<!http://)(www'.'S+)|", "http://$1", $text_with_hyperlink);

将它放在<a>之前添加代码,它将把所有www.links.com转换为http://www.links.com

也许这就是您想要的:http://snippets.dzone.com/posts/show/6156

//编辑:这个呢:

<?php
$body = $_GET['body'];
$pattern = "/(''s+)((?:[a-z][a-z''.''d''-]+)''.(?:[a-z][a-z''-]+))(?![''w''.])/is";
$text_with_hyperlink = preg_replace($pattern, '<a href="http://''0" class="oembed">'0</a>', $body);
$text_with_hyperlink = preg_replace("/(http)(:)(''/)(''/)(''s+)/is", "http://", $text_with_hyperlink);
echo $text_with_hyperlink;
?>

(很脏,我知道…)