用于将URL自动转换为可单击的超链接(锚定标记)的函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用于将URL自动转换为可单击的超链接(锚定标记)的函数相关的知识,希望对你有一定的参考价值。

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);
  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#$%&~/.-;:=,[email protected][]+]*)#is', '_make_url_clickable_cb', $ret);
  34. $ret = preg_replace_callback('#([s>])((www|ftp).[w\x80-\xff#$%&~/.-;:=,[email protected][]+]*)#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自动转换为可单击的超链接(锚定标记)的函数的主要内容,如果未能解决你的问题,请参考以下文章

PHP 自动将URL转换为可点击超链接(锚标记)的功能

将Twitter状态上的链接转换为可单击的url。加@和#

WordPress使用make_clickable函数让文章网址URL自动生成超链接

Highcharter 中的超链接条形图

通过绑定在TextBlock中创建超链接

将字符串转换为可单击的URL