Activate Links in String PHP


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

Returns the same string, except with links wrapped in <a href=""> tags. Works on www.snipplr.com and on http://snipplr.com

A variation of the script on the attached URL.


Copy this code and paste it in your HTML
  1. function activateLinks($string)
  2. {
  3. /*
  4. // This regular expression looks for <strong>http:// </strong>type url
  5. $string = preg_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
  6. '<a href="1" target=_blank>$0$1$2$3</a>', $string);
  7.  
  8. // This regular expression looks for <strong>www. </strong>type url
  9. $string = preg_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
  10. '1<a href="http://2" target=_blank>$0$1$2$3</a>', $string);
  11.  
  12. // This regular expression looks for <strong>[email protected]</strong>
  13. $string = preg_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
  14. '<a href="mailto:1" target=_blank>$0$1$2$3</a>', $string);
  15. */
  16.  
  17. $m = preg_match_all('/http:\/\/[a-z0-9A-Z.]+(?(?=[\/])(.*))/', $string, $match);
  18.  
  19. if ($m) {
  20. $links=$match[0];
  21. for ($j=0;$j<$m;$j++) {
  22. $string=str_replace($links[$j],'<a href="'.$links[$j].'">'.$links[$j].'</a>',$string);
  23. }
  24. }
  25.  
  26. $m = preg_match_all('(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', $string, $match);
  27.  
  28. if ($m) {
  29. $links=$match[0];
  30. for ($j=0;$j<$m;$j++) {
  31. $string=str_replace($links[$j],'<a href="'.$links[$j].'">'.$links[$j].'</a>',$string);
  32. }
  33. }
  34.  
  35. return $string;
  36.  
  37. }

URL: http://www.php.net/manual/en/function.preg-match-all.php#103552

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.