preg a simple solution?
Posted: Fri Apr 16, 2004 11:24 am
I'm sure most of us have been here before, i.e. we get too tied up looking for the complex solution and completely miss the simple aproach.
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.....
Which at present is working OK it will return......
You can see the actual visible link part is truncated. It is still work in progress and the actual regex I'm sure I can refine somewhat, but is there a more simplistict approach. I'm not looking so much for code examples more general ideas.
Any thoughts?
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?