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;
}
if (strlen($result) > $length)
特にコードの重複ブロックは、ハックのようです。完全に削除することを検討しましたが、スキーム、ユーザー、パス、およびポートparse_url()
を無視したいと思います。
同じ効果を持つ、よりエレガントで整理されたソリューションを思いつくことができるかどうか疑問に思っています。
気付いたのですが、バグがあります -$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) . '...';
}