Automatically turn all text urls into working Hyperlinks


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

Does not require http in the text to link. It must start with www however. Optionaly make the links popup in a new window.


Copy this code and paste it in your HTML
  1. /**
  2.  * AutoLinkUrls()
  3.  *
  4.  * @param mixed $str
  5.  * @param bool $popup
  6.  * @return void
  7.  */
  8. function AutoLinkUrls($str,$popup = FALSE){
  9. if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)){
  10. $pop = ($popup == TRUE) ? " target=\"_blank\" " : "";
  11. for ($i = 0; $i < count($matches['0']); $i++){
  12. $period = '';
  13. if (preg_match("|\.$|", $matches['6'][$i])){
  14. $period = '.';
  15. $matches['6'][$i] = substr($matches['6'][$i], 0, -1);
  16. }
  17. $str = str_replace($matches['0'][$i],
  18. $matches['1'][$i].'<a href="http'.
  19. $matches['4'][$i].'://'.
  20. $matches['5'][$i].
  21. $matches['6'][$i].'"'.$pop.'>http'.
  22. $matches['4'][$i].'://'.
  23. $matches['5'][$i].
  24. $matches['6'][$i].'</a>'.
  25. $period, $str);
  26. }//end for
  27. }//end if
  28. return $str;
  29. }//end AutoLinkUrls

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.