php switch case语句来处理范围

nik*_*hil 37 php range switch-statement

我正在解析一些文本并根据一些规则计算权重.所有角色都具有相同的重量.这会使switch语句真的很长,我可以在case语句中使用范围.

我看到了一个提倡关联数组的答案.

$weights = array(
[a-z][A-Z] => 10,
[0-9] => 100,
['+','-','/','*'] => 250
);
//there are more rules which have been left out for the sake of clarity and brevity
$total_weight = 0;
foreach ($text as $character)
{
  $total_weight += $weight[$character];
}
echo $weight;
Run Code Online (Sandbox Code Playgroud)

实现这样的目标的最佳方法是什么?是否有类似于PHP中的bash case语句?当然,在关联数组或switch语句中写下每个字符都不是最优雅的解决方案,还是唯一的替代方案?

Sud*_*oti 151

好吧,你可以在switch语句中有以下范围:

//just an example, though
$t = "2000";
switch (true) {
  case  ($t < "1000"):
    alert("t is less than 1000");
  break
  case  ($t < "1801"):
    alert("t is less than 1801");
  break
  default:
    alert("t is greater than 1800")
}

//OR
switch(true) {
   case in_array($t, range(0,20)): //the range from range of 0-20
      echo "1";
   break;
   case in_array($t, range(21,40)): //range of 21-40
      echo "2";
   break;
}
Run Code Online (Sandbox Code Playgroud)


ako*_*ond 2

$str = 'This is a test 123 + 3';

$patterns = array (
    '/[a-zA-Z]/' => 10,
    '/[0-9]/'   => 100,
    '/[\+\-\/\*]/' => 250
);

$weight_total = 0;
foreach ($patterns as $pattern => $weight)
{
    $weight_total += $weight * preg_match_all ($pattern, $str, $match);;
}

echo $weight_total;
Run Code Online (Sandbox Code Playgroud)

*更新:使用默认值*

foreach ($patterns as $pattern => $weight)
{
    $match_found = preg_match_all ($pattern, $str, $match);
    if ($match_found)
    {
        $weight_total += $weight * $match_found;
    }
    else
    {
        $weight_total += 5; // weight by default
    }
}
Run Code Online (Sandbox Code Playgroud)