URL to HTML link PHP parser


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



Copy this code and paste it in your HTML
  1. function parseURLs($str, $length = 15){
  2. preg_match_all('@(https?://([-\w\.]+)+(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?)@',$str,$matches);
  3. if($matches){
  4. foreach($matches[0] as $url){
  5. $text = $length ? shortText($url,$length) : $url;
  6. $replace = '<a href="'.$url.'">'.$text.'</a>';
  7. $str = str_replace($url,$replace,$str);
  8. }
  9. }
  10. return $str;
  11. }
  12.  
  13. function shortText($text, $chars){
  14. $str = $text;
  15. if(strlen($str) > $chars){
  16. $str = substr($str, 0, $chars);
  17. $str .= "...";
  18. return $str;
  19. }else {
  20. return $str;
  21. }
  22. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.