Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

php - How to add anchor tag to a URL from text input

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.

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

<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>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

One example found online follows:

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

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  = '#(([w-]+://?|www[.])[^s()<>]+(?:([wd]+)|([^[: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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...