I can't help feeling I'm missing the more simplistict approach with this one...
The problem is to take a url from a text string and convert it to a clickable link, at the same time truncate it's length if it is over a certain length. i.e. those long links people post to ebay auctions.
So I spent about an hour on this but I'm getting the feeling I'm missing something. Heres the code.....
Code: Select all
<?php
function url2link($text)
{
$html = " ".$text;
$html = preg_replace_callback("/\b([a-z]+:\/\/(?:[-\w]{2,}\.)*[-\w]{2,}(?::\d+)?(?:(?:[^\s;,.?"'[\](){}<>]|\S[^\s;,.?"'[\](){}<>])*)?)/i",
create_function('$match', 'return short_url($match[1], 7);'), $html);
$html = preg_replace_callback("/([^\/])((?:www|ftp)\.(?:[-\w]{2,}\.)+[-\w]{2,}(?::\d+)?(?:(?:[^\s;,.?"'[\](){}<>]|\S[^\s;,.?"'[\](){}<>])*)?)/i",
create_function('$match', 'return short_url($match[2], 0,$match[1], "http://");'), $html);
return substr($html, 1);
}
function short_url($url, $offset = 0, $prepend = '', $scheme = '')
{
$truncated = $url;
if (strlen($url) > 40 + $offset)
{
$truncated = substr($url, 0, 20 + $offset) . '...' . substr($url, -20);
}
return $prepend . '<a href="' . $scheme . $url . '">' . $truncated . '</a>';
}
$test_text = 'Hey check this deal on ebay http://cgi.ebay.com/ebaymotors/ws/eBayI ... 106&rd=1';
echo url2link($test_text);
?>Code: Select all
Hey check this deal on ebay <a href="http://cgi.ebay.com/ebaymotors/ws/eBayISAPI.dll?ViewItem&category=50019&item=2473512106&rd=1">http://cgi.ebay.com/ebaymot...item=2473512106&rd=1</a>Any thoughts?