php switch case语句来处理范围

php switch case statement to handle ranges(php switch case语句来处理范围)
本文介绍了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语句来处理范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)