[英]Detect URL in text without hyperlink and replace normal URL with hyperlink?
[英]Detect a hyperlink in a text - jQuery
我有一個純文本,說, "Hello how are you, please visit 'http://google.com'"
。
我使用 jQuery 在 div 中顯示它(此文本是隨機生成的)。 我的問題是,有什么方法可以檢測到文本中的“http://google.com”是一個超鏈接,從而將文本的那部分轉換為可點擊的超鏈接?
謝謝。
如果您使用 jQuery,您應該查看 linkify,它會自動為您完成。
$("#content").linkify();
來源: https : //code.google.com/archive/p/jquery-linkify/
在這里:
http
://www.dave-smith.info/jquery.linkify/ ( 在 web.archive.org 上的鏡像)
這個正則表達式對我有用(用於匹配 URL 的改進的自由、准確的正則表達式模式的稍微修改版本)。
text = text.replace(
/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]
|[a-z0-9.-]+[.][a-z]{2,4}\/)(?:(?:[^\s()<>.]+[.]?)+|((?:[^\s()<>]+
|(?:([^\s()<>]+)))))+(?:((?:[^\s()<>]+|(?:([^\s()<>]+))))
|[^\s`!()[]{};:'".,<>?«»“”‘’]))/gi,
"<a target=_blank href=$1>$1</a>");
我知道已經晚了。 我到處搜索以找到答案。 你可以試試這個。
var get_words = 'This is a long text. It contains 150 characters. You can find more about this text on this link http://www.somewebsite.com/RDFCCSDVDS';
$('p').html(beautify_text(get_words));
function beautify_text(text){
var $words = text.split(' ');
for (i in $words) {
if ($words[i].indexOf('http://') == 0) {
$words[i] = '<a href="' + $words[i] + '" target="_blank">' + $words[i] + '</a>';
}
}
return $words.join(' ');
}
您可以通過執行以下操作來實現此目的:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "Hello how are you, please visit http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
這是一個完整的教程: 在文本中查找 URL 並制作鏈接
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.