如何将锚标记添加到来自文本输入的URL [英] How to add anchor tag to a URL from text input

查看:106
本文介绍了如何将锚标记添加到来自文本输入的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to take user inputted text in a comment field and check for URL type expression, and if it exists, add an anchor tag (to url) when the comment is displayed.

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

I am using PHP on the server-side, and Javascript (with jQuery) on client, so should I wait to check for URL until right before it is displayed? Or add the anchor tag before inserting it in the database?

so

so

<textarea id="comment">check out blahblah.com or www.thisthing.co.uk or http://checkthis.us/</textarea>  

变为

becomes

<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>


推荐答案

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

First, a request. Don't do this before writing the data to the database. Instead, do it before displaying the data to the end-user. This will cut down on all confusion, and will allow you more flexibility in the future.

一个例子 online online

One example found online follows:

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

更彻底的 daringfireball.net

And a much more thorough one from 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);
}

这篇关于如何将锚标记添加到来自文本输入的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆