autolink.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Adapted from https://plugins.trac.wordpress.org/browser/sem-external-links/trunk/sem-autolink-uri.php
  4. * which is MIT/GPL licenced.
  5. * Author: Denis de Bernardy & Mike Koepke
  6. * Author URI: https://www.semiologic.com
  7. */
  8. class AutoLinkExtension {
  9. public static function auto_link_text(string $string) {
  10. $string = preg_replace_callback(
  11. "/
  12. ((?<![\"']) # don't look inside quotes
  13. (\b
  14. ( # protocol or www.
  15. [a-z]{3,}:\/\/
  16. |
  17. www\.
  18. )
  19. (?: # domain
  20. [a-zA-Z0-9_\-]+
  21. (?:\.[a-zA-Z0-9_\-]+)*
  22. |
  23. localhost
  24. )
  25. (?: # port
  26. \:[0-9]+
  27. )?
  28. (?: # path
  29. \/[a-z0-9:%_|~.-]*
  30. (?:\/[a-z0-9:%_|~.-]*)*
  31. )?
  32. (?: # attributes
  33. \?[a-z0-9:%_|~.=&#;-]*
  34. )?
  35. (?: # anchor
  36. \#[a-z0-9:%_|~.=&#;-]*
  37. )?
  38. )
  39. (?![\"']))
  40. /ix",
  41. function ($match) {
  42. $url = $match[0];
  43. $href = $url;
  44. if (false === strpos($href, 'http')) {
  45. $href = 'http://' . $href;
  46. }
  47. return '<a href="' . $href . '" rel="noreferrer">' . $url . '</a>';
  48. },
  49. $string
  50. );
  51. return $string;
  52. }
  53. }