Parse urls()

From Lankyland

Jump to: navigation, search

Contents

What is Does

This function will parse a string and turn any URLs into HTML Hyperlinks. It also has the option to concatenate the displayed URL length and if it opens a new window, same window or a specific window.

The Code

 function parse_urls($text,$maxurl_len = 35, $target = '_blank')
 {
 if(preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si', $text, $urls))
 {
   $offset1 = ceil(0.65 * $maxurl_len) - 2;
   $offset2 = ceil(0.30 * $maxurl_len) - 1;
 
   foreach(array_unique($urls[1]) AS $url)
   {
     if($maxurl_len AND strlen($url) > $maxurl_len)
     {
       $urltext = substr($url, 0, $offset1) . '...' . substr($url, -$offset2);
     }
     else
     {
       $urltext = $url;
     }
 
     $text = str_replace($url, '<a href="'. $url .'" target="'. $target .'" title="'. $url .'">'. $urltext .'</a>', $text);
   }
 }
 
 return $text;
 }

How it Works

Pass the string to the function and it will go through it looking for http, ftp or similar and it will then rewrite that part of the string to include <a href="$url" target="specific target">$urltext</a>. It will also limit the $urltext in its full version or if too long, in a concatentated version, eg: http://www.too...om.au/long.exe

Examples

Take the following string:

 $string = "This is a string that we have pulled from a database and it contains a link to http: //anartechsystems.com/somereallylongfilenamethatyoucannotremember.mp3
 but it is not a hyperlink if we were to just echo that out"

When we pass the sting to our function like this:

 parse_url($string);

We should get the following raw text:

 $string = "This is a string that we have pulled from a database and it contains a link
 to <a href="http: //anartechsystems.com/somereallylongfilenamethatyoucannotremember.mp3" target="_blank">http: //anartec...member.mp3</a> but it is not a hyperlink if we were to
 just echo that out"
Personal tools
Donate
Donate towards my web hosting bill!