Posted By

ptejada on 06/27/10


Tagged

url php link html parser


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

garretjames


URL to HTML link PHP parser


 / Published in: PHP
 

  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  

You need to login to post a comment.