PHP的开关案例声明

PHP的开关案例声明

本文介绍了PHP的开关案例声明,以处理范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一些文本并根据一些规则计算权重.所有字符具有相同的权重.这样可以使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的开关案例声明,以处理范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:49