Forum Moderators: coopster

Message Too Old, No Replies

shorten long url in a regular expression

         

eltreno

9:35 am on May 3, 2007 (gmt 0)

10+ Year Member



Hi
I am using the function below I fould to create anchor tags of links in paragraph text.

It work fine but long url's obviously stretch the page.

Is there a way to shorten the link text in this reqular expression.

echo find_url(createParas(htmlentities($_POST['content'])));

function find_url($string){
//"www."
$pattern_preg1 = '#(^¦\s)(www¦WWW)\.([^\s<>\.]+)\.([^\s\n<>]+)#sm';
$replace_preg1 = '\\1<a href="http://\\2.\\3.\\4" target="_blank" class="link">\\2.\\3.\\4</a>';

//"http://"
$pattern_preg2 = '#(^¦[^\"=\]]{1})(http¦HTTP¦ftp)(s¦S)?://([^\s<>\.]+)\.([^\s<>]+)#sm';
$replace_preg2 = '\\1<a href="\\2\\3://\\4.\\5" target="_blank" class="link">\\2\\3://\\4.\\5</a>';

$string = preg_replace($pattern_preg1, $replace_preg1, $string);
$string = preg_replace($pattern_preg2, $replace_preg2, $string);

return $string;
}

Cheers
Trent

coopster

3:54 pm on May 3, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could capture just a smaller portion of the url string, domain name perhaps, and use that in the replacement as opposed to the entire url. Another option would be to run it through a callback function to determine the length of the replacement string and if it goes beyond a certain acceptable length, then use just a portion of the string.

eltreno

6:31 pm on May 4, 2007 (gmt 0)

10+ Year Member



In case anyone wants this solution, I have created this

It's creates anchor tags like above but then looks for urls over (x) characters in length and if so replace them with More info >>

Tried to replace with domain but realised you still may get caught with long domain if you working with small nav area or something

//$string - text to replace urls in
//$x - max length a url can be -5

function find_url($string, $x){
//"www."
$pattern_preg1 = '#(^¦\s)(www¦WWW)\.([^\s<>\.]+)\.([^\s\n<>]+)#sm';
$replace_preg1 = '\\1<a href="http://\\2.\\3.\\4\\5" target="_blank" class="link">\\2.\\3.\\4\\5</a>';

//"http://"
$pattern_preg2 = '#(^¦[^\"=\]]{1})(http¦HTTP¦ftp)(s¦S)?://([^\s<>\.]+)\.([^\s<>]+)#sm';
$replace_preg2 = '\\1<a href="\\2\\3://\\4.\\5\\6" target="_blank" class="link">\\4.\\5\\6</a>';//\\2\\3://

$string = preg_replace($pattern_preg1, $replace_preg1, $string);
$string = preg_replace($pattern_preg2, $replace_preg2, $string);

//SHORTEN, if over x characters (x is max length of chars across screen minus 10 to be safe (NOTE: x count won't include the 4 bytes of 'www.' )
$pattern_preg3 = '/">www.[^\s<>]{'. $x .',}(<\/a>)/';
$replace_preg3 = '">More info >></a>';

$string = preg_replace($pattern_preg3, $replace_preg3, $string);

return $string;
}

Cheers