From my related question here at SO I've come up with the following PHP snippet:
$url = parse_url($url);
if (is_array($url))
{
$depth = 2;
$length = 50;
if (array_key_exists('host', $url))
{
$result = preg_replace('~^www[.]~i', '', $url['host']);
if (array_key_exists('path', $url))
{
$result .= preg_replace('~/+~', '/', $url['path']); // normalize a bit
}
if (array_key_exists('query', $url))
{
$result .= '?' . $url['query'];
}
if (array_key_exists('fragment', $url))
{
$result .= '#' . $url['fragment'];
}
if (strlen($result) > $length)
{
$result = implode('/', array_slice(explode('/', $result, $depth + 2), 0, $depth + 1)) . '/';
if (strlen($result) > $length)
{
$result = implode('/', array_slice(explode('/', $result, $depth + 1), 0, $depth + 0)) . '/';
}
$result = substr($result, 0, $length) . '...';
}
}
return $result;
}
Seems kinda hackish, specially the duplicate if (strlen($result) > $length)
blocks of code. I've considered dropping parse_url()
altogether, but I want to ignore the scheme, user, pass and port.
I'm wondering if you guys can come up with a more elegant / organized solution that has the same effect.
I just noticed, there is a bug - if $depth != 2
the following block is affected:
if (strlen($result) > $length)
{
$result = implode('/', array_slice(explode('/', $result, $depth + 2), 0, $depth + 1)) . '/';
if (strlen($result) > $length)
{
$result = implode('/', array_slice(explode('/', $result, $depth + 1), 0, $depth + 0)) . '/';
}
$result = substr($result, 0, $length) . '...';
}
I think the best solution is to use a loop, I'll try to fix this ASAP. :S
Solved it, by replacing it with this new snippet:
if (strlen($result) > $length)
{
for ($i = $depth; $i > 0; $i--)
{
$result = implode('/', array_slice(explode('/', $result), 0, $i + 1)) . '/';
if (strlen($result) <= $length)
{
break;
}
}
$result = substr($result, 0, $length) . '...';
}