我怎么能用更短的方式写这个?

时间:2011-11-22 01:39:16

标签: php

此代码重复。我怎样才能缩短它?也许通过使用匿名函数或其他东西?

foreach ($value as $wrong) {
  if (starts_with($wrong, '%') and ends_with($wrong, '%')) {
    $wrong = trim($wrong, '%');
    if (contains($address, $wrong)) {
      $corrected_address = str_replace($wrong, $key, $address);
      break;
    }
  }
  else {
    $wrong = trim($wrong, '%');
    if (ends_with($address, $wrong)) {
      $corrected_address = str_replace($wrong, $key, $address);
      break;
    }
  }
}

感谢。

3 个答案:

答案 0 :(得分:2)

这是我对更短版本的抨击:

foreach ($value as $wrong) {
   $both  = starts_with($wrong, '%') && ends_with($wrong, '%');
   $wrong = trim($wrong, '%');
   if ($both ? contains($address, $wrong) : ends_with($address, $wrong)) {
      $corrected_address = str_replace($wrong, $key, $address);
      break;
   }
}

$both可能应该重命名为更具描述性的内容。

答案 1 :(得分:1)

这个怎么样:

foreach ($value as $wrong) { 
  $wrong = trim($wrong, '%');

  if (starts_with($wrong, '%') && ends_with($wrong, '%')) { 

    if (contains($address, $wrong)) { 
      $corrected_address = str_replace($wrong, $key, $address); 
      break; 
    } 

  }elseif (ends_with($address, $wrong)) { 
      $corrected_address = str_replace($wrong, $key, $address); 
      break; 
  } 
} 

答案 2 :(得分:1)

如果您在第一个之后破裂,则不需要循环。您可以使用array_filter获取匹配项,然后使用第一个匹配项执行某些操作。

$trimmed = array_map(function($x){return trim($x,'%');}, $value);
$matches = array_filter($trimmed, function($x){return contains($GLOBALS["address"],$x);});
$wrong = array_shift($matches);
$corrected_address = str_replace($wrong, $key, $address);

顺便说一下,请注意array_map如何首先获取回调而第二个数组接受回调,但array_filter是否会反转?这样的事情让我避免使用php。