检测文本中的超链接- jQuery

Detect a hyperlink in a text - jQuery

本文关键字:jQuery 超链接 文本 检测      更新时间:2023-09-26

我有一个纯文本,例如"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/(mirror at 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>");

I know it's late. I've search anywhere to find an answer. You can try this.

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并创建链接