如何从文本输入向URL添加锚标记

Dou*_*las 11 html javascript php jquery

我希望能够在注释字段中获取用户输入的文本并检查URL类型表达式,如果存在,则在显示注释时添加锚标记(到url).

我在服务器端使用PHP,在客户端使用Javascript(使用jQuery),所以我应该等到它显示之前检查URL吗?或者在将锚标记插入数据库之前添加它?

所以

<textarea id="comment">check out blahblah.com or www.thisthing.co.uk or http://checkthis.us/</textarea>  
Run Code Online (Sandbox Code Playgroud)

<div id="commentDisplay">check out <a href="blahblah.com">blahblah.com</a> or <a href="www.thisthing.co.uk">www.thisthing.co.uk</a> or <a href="http://checkthis.us/">http://checkthis.us/</a></div>
Run Code Online (Sandbox Code Playgroud)

Sam*_*son 22

首先是请求.在将数据写入数据库之前不要这样做.相反,在向最终用户显示数据之前执行此操作.这将减少所有混乱,并将在未来为您提供更大的灵活性.

在线发现的一个例子如下:

$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
Run Code Online (Sandbox Code Playgroud)

来自daringfireball.net的更彻底的一个:

/**
 * Replace links in text with html links
 *
 * @param  string $text
 * @return string
 */
function auto_link_text($text)
{
   $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
   $callback = create_function('$matches', '
       $url       = array_shift($matches);
       $url_parts = parse_url($url);

       $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
       $text = preg_replace("/^www./", "", $text);

       $last = -(strlen(strrchr($text, "/"))) + 1;
       if ($last < 0) {
           $text = substr($text, 0, $last) . "&hellip;";
       }

       return sprintf(\'<a rel="nowfollow" href="%s">%s</a>\', $url, $text);
   ');

   return preg_replace_callback($pattern, $callback, $text);
}
Run Code Online (Sandbox Code Playgroud)

  • @JonathanSampson 当我使用没有“http://”的域名的第二个函数时,它会将当前域名附加到开头。例如:如果我输入 www.google.com,它会显示为 www.mydomain.com/www.google.com (2认同)

mar*_*rkd 13

我改编了Jonathan Sampson的正则表达式选项,以便它对什么是域名更加宽容(不需要http(s)来限定).

function hyperlinksAnchored($text) {
    return preg_replace('@(http)?(s)?(://)?(([-\w]+\.)+([^\s]+)+[^,.\s])@', '<a href="http$2://$4">$1$2$3$4</a>', $text);
}
Run Code Online (Sandbox Code Playgroud)

适用于这些URL(并成功地省略了尾随句点或逗号):

http://www.google.com/
https://www.google.com/.
www.google.com
www.google.com.
www.google.com/test
google.com
google.com,
google.com/test
123.com/test
www.123.com.au
ex-ample.com
http://ex-ample.com
http://ex-ample.com/test-url_chars.php?param1=val1.
http://ex-ample.com/test-url_chars?param1=value1&param2=val+with%20spaces
Run Code Online (Sandbox Code Playgroud)

希望能帮助别人.