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) . "…";
}
return sprintf(\'<a rel="nowfollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
Run Code Online (Sandbox Code Playgroud)
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¶m2=val+with%20spaces
Run Code Online (Sandbox Code Playgroud)
希望能帮助别人.