Linkify.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. /**
  3. * Injector that converts http, https and ftp text URLs to actual links.
  4. */
  5. class HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector
  6. {
  7. public $name = 'Linkify';
  8. public $needed = array('a' => array('href'));
  9. public function handleText(&$token) {
  10. if (!$this->allowsElement('a')) return;
  11. if (strpos($token->data, '://') === false) {
  12. // our really quick heuristic failed, abort
  13. // this may not work so well if we want to match things like
  14. // "google.com", but then again, most people don't
  15. return;
  16. }
  17. // there is/are URL(s). Let's split the string:
  18. // Note: this regex is extremely permissive
  19. $bits = preg_split('#((?:https?|ftp)://[^\s\'"<>()]+)#S', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
  20. $token = array();
  21. // $i = index
  22. // $c = count
  23. // $l = is link
  24. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  25. if (!$l) {
  26. if ($bits[$i] === '') continue;
  27. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  28. } else {
  29. $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));
  30. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  31. $token[] = new HTMLPurifier_Token_End('a');
  32. }
  33. }
  34. }
  35. }
  36. // vim: et sw=4 sts=4