从my related question在这里所以我想出了下面的PHP代码片段:此片段是否可以进一步优化/组织?
$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;
}
似乎有点hackish的,专门的代码重复if (strlen($result) > $length)
块。我认为下降parse_url()
干脆,但我想忽略方案,用户,通和端口。
我想知道如果你们能想出一个更优雅/有组织的解决方案,具有相同的效果。
我只注意到,有一个bug - 如果$depth != 2
以下块受到影响:
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) . '...';
}
我认为最好的办法是使用一个循环,我会尽力尽快解决这个问题。 :S
解决了这个问题,通过这种新的代码片段替换它:
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) . '...';
}
这是一种习惯,我总是用严格的比较。现在修复。 – 2010-01-14 13:00:36