Function to Auto Convert URL into Clickable Hyperlink (Anchor Tag)


/ Published in: PHP
Save to your folder(s)

In wordpress, if you want to auto convert all URLs in your string into clickable hyperlinks, you can actually do it using the built-in function make_clickable().

If you need to do that outside of wordpress, you can use the same function.
Example:
$string = 'I have some texts here and also links such as http://www.youtube.com , www.haha.com and [email protected]. They are ready to be replaced.';

echo make_clickable($string);


Copy this code and paste it in your HTML
  1. function _make_url_clickable_cb($matches) {
  2. $ret = '';
  3. $url = $matches[2];
  4. if ( empty($url) )
  5. return $matches[0];
  6. // removed trailing [.,;:] from URL
  7. if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
  8. $ret = substr($url, -1);
  9. $url = substr($url, 0, strlen($url)-1);
  10. }
  11. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
  12. }
  13. function _make_web_ftp_clickable_cb($matches) {
  14. $ret = '';
  15. $dest = $matches[2];
  16. $dest = 'http://' . $dest;
  17. if ( empty($dest) )
  18. return $matches[0];
  19. // removed trailing [,;:] from URL
  20. if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
  21. $ret = substr($dest, -1);
  22. $dest = substr($dest, 0, strlen($dest)-1);
  23. }
  24. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
  25. }
  26. function _make_email_clickable_cb($matches) {
  27. $email = $matches[2] . '@' . $matches[3];
  28. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  29. }
  30. function make_clickable($ret) {
  31. $ret = ' ' . $ret;
  32. // in testing, using arrays here was found to be faster
  33. $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
  34. $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
  35. $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
  36. // this one is not in an array because we need it to run last, for cleanup of accidental links within links
  37. $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
  38. $ret = trim($ret);
  39. return $ret;
  40. }

URL: http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.