在大多数聊天应用程序中,当用户输入超链接时,它会自动在聊天窗口中变成可点击的。如何使用PHP/JJavaScript/JQuery复制这种行为?
从本质上讲,我的想法是测试聊天消息字符串中的超链接,并将它们封装在<a href>
标签中,并将其本身作为链接。这是正确的吗?如果是,我该怎么做?此外,我该如何使链接在新的选项卡中打开,而不是替换我的页面?
EDIT 这花了我很多时间,但这个PHP函数应该适用于所有现实场景:
function formatTextLinks($text) {
$words = preg_split("/['s,]+/", $text);
$offset = 0;
foreach($words as $value) {
preg_match("/^(https?:'/'/)?(['da-z'.-]+)'.([a-z'.]{2,6})(['/'w '.-]*)*'/?$/", $value, $matches);
$s = $matches[0];
if(!is_string($s)) continue;
$pos = strpos($text, $s, $offset);
if($pos !== false) {
$helper = "";
if(strpos($s, "http://") === false || strpos($s, "https://") === false) $helper = "http://";
$text = substr_replace($text, "<a href='".$helper.$s."' target='_blank'>".$s."</a>", $pos, strlen($s));
$offset = $pos + strlen("<a href='".$helper.$s."' target='_blank'>".$s."</a>");
}
}
return $text;
}
您可以使用php或javascript正则表达式来测试它是否是URL(链接)。如果是,使用jquery创建一个html链接标记。
这是正则表达式模式
/^(https?:'/'/)?(['da-z'.-]+)'.([a-z'.]{2,6})(['/'w '.-]*)*'/?$/
这是来源http://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149