php switch case语句来处理范围
我正在解析一些文本并根据一些规则计算权重.所有角色的权重都相同.这会使 switch 语句很长我可以在 case 语句中使用范围吗?
I'm parsing some text and calculating the weight based on some rules. All the characters have the same weight. This would make the switch statement really long can I use ranges in the case statement.
我看到一个提倡关联数组的答案.
I saw one of the answers advocating associative arrays.
$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 语句中写下每个单独的字符肯定不是最优雅的解决方案,还是唯一的选择?
What is the best way to achieve something like this? Is there something similar to the bash case statement in php? Surely writing down each individual character in either the associative array or the switch statement can't be the most elegant solution or is it the only alternative?
推荐答案
$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
}
}
相关文章