根据我在 SO 的相关问题,我提出了以下 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;
}
似乎有点骇人听闻,特别是重复if (strlen($result) > $length)
的代码块。我考虑过完全放弃parse_url()
,但我想忽略scheme、user、pass和port。
我想知道你们是否可以想出一个更优雅/更有条理的解决方案,具有相同的效果。
我刚刚注意到,有一个错误 - 如果$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) . '...';
}