php 切换大小写语句来处理范围

2022-08-30 10:47:49

我正在解析一些文本并根据一些规则计算权重。所有字符具有相同的权重。这将使 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;

实现此类目标的最佳方法是什么?有没有类似于php中的bash case语句?当然,在关联数组或 switch 语句中写下每个单独的字符可能不是最优雅的解决方案,或者它是唯一的选择?


答案 1

好吧,您可以在 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;
}

答案 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;

*更新:默认值 *

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
    }
}

推荐