php switch case语句来处理范围 [英] php switch case statement to handle ranges

查看:93
本文介绍了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
    }
}

这篇关于php switch case语句来处理范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆