2010-01-14 37 views
0

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) . '...'; 
} 

回答

0

这里是我想出了一个更简洁的版本:

$url = preg_replace('~^www[.]~i', 'http://www.', array_shift($url)); 
$parts = parse_url($url); 

if (is_array($parts)) 
{ 
    $depth = 2; 
    $length = 50; 

    if (array_key_exists('host', $parts)) 
    { 
     $result = preg_replace('~^www[.]~i', '', $parts['host']); 

     if (array_key_exists('path', $parts)) 
     { 
      $result .= preg_replace('~/+~', '/', $parts['path']); 
     } 

     if (array_key_exists('query', $parts)) 
     { 
      $result .= '?' . $parts['query']; 
     } 

     if (array_key_exists('fragment', $parts)) 
     { 
      $result .= '#' . $parts['fragment']; 
     } 

     if (strlen($result) > $length) 
     { 
      while ($depth > 0) 
      { 
       $result = implode('/', array_slice(explode('/', $result), 0, $depth-- + 1)) . '/'; 

       if (strlen($result) <= $length) 
       { 
        break; 
       } 
      } 

      $result = substr($result, 0, $length) . '...'; 
     } 

     return $result; 
    } 
} 
2

对于初学者来说,你可以有:

if (is_array($url)) 

重复您的所有=== true操作。你为什么比较类型?

+0

这是一种习惯,我总是用严格的比较。现在修复。 – 2010-01-14 13:00:36