Can this snippet be further optimized / organized?

jersey

New Member
From my related question here at SO I've come up with the following PHP snippet:\[code\]$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;}\[/code\]Seems kinda hackish, specially the duplicate \[code\]if (strlen($result) > $length)\[/code\] blocks of code. I've considered dropping \[code\]parse_url()\[/code\] 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 \[code\]$depth != 2\[/code\] the following block is affected:\[code\]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) . '...';}\[/code\]I think the best solution is to use a loop, I'll try to fix this ASAP. :SSolved it, by replacing it with this new snippet:\[code\]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) . '...';}\[/code\]
 
Back
Top