繁体   English   中英

php switch 语句在字符串中带有通配符

[英]php switch statement with wildcard in the string

我想要一个switch 语句,其中包含文字情况和字符串中带有通配符的情况:

switch($category){
    case 'A**': $artist= 'Pink Floyd'; break;
    case 'B**': $artist= 'Lou Reed'; break;
    case 'C01': $artist= 'David Bowie'; break;
    case 'C02': $artist= 'Radiohead'; break;
    case 'C03': $artist= 'Black Angels'; break;
    case 'C04': $artist= 'Glenn Fiddich'; break;
    case 'C05': $artist= 'Nicolas Jaar'; break;
    case 'D**': $artist= 'Flat Earth Society'; break;
}

当然,* 将在此处按字面意思表示,因为我将其定义为字符串,所以这不起作用,但你知道我想要完成什么:对于 A、B 和 D 情况,数字可以是任何 (*)。 也许使用 preg_match 这是可能的,但这真的让我大吃一惊。 我用谷歌搜索,我真的做到了。

尝试这个:

$rules = [
    '#A(.{2,2})#' => 'Pink Floyd',
    '#B(.{2,2})#' => 'Lou Reed',
    'C01' => 'David Bowie',
    'C02' => 'Radiohead',
    'C03' => 'Black Angels',
    'C04' => 'Glenn Fiddich',
    'C05' => 'Nicolas Jaar',
    '#D(.{2,2})#' => 'Flat Earth Society'
];

$category = 'Dxx';
$out = '';

foreach ( $rules as $key => $value )
{
    /* special case */
    if ( $key[0] === '#' )
    {
        if ( !preg_match($key, $category) )
            continue;

        $out = $value;
        break;
    }
    
    /* Simple key */
    if ( $key === $category )
    {
        $out = $value;
        break;
    }
}

echo $out."\n";

当然,您可以使用 switch 来做到这一点,前提是它确实是最好的方法。 很长的切换案例列表令人头疼......

switch($category){
    case 'C01': $artist = 'David Bowie';    break;
    case 'C02': $artist = 'Radiohead';      break;
    case 'C03': $artist = 'Black Angels';   break;
    case 'C04': $artist = 'Glenn Fiddich';  break;
    case 'C05': $artist = 'Nicolas Jaar';   break;
    default:
        switch(substr($category,0,1)){
            case A: $artist = 'Pink Floyd';         break;
            case B: $artist = 'Lou Reed';           break;
            case D: $artist = 'Flat Earth Society'; break;
            default:    echo'somethig is wrong with category!';}}

我写了一个 function。 这是preg_match但它很短且可重复使用。

function preg_switch(string $str, array $rules) {
    foreach($rules as $key => $value) {
        if(preg_match("/(^$key$)/", $str) > 0)
            return $value;
    }
    return null;
}

你可以像这样使用它:

$artist = preg_switch("Bdd", [
    "A.." => "Pink Floyd",
    "B.." => "Lou Reed",
    "C01" => "David Bowie",
    "C02" => "Radiohead",
    "C03" => "Black Angels",
    "C04" => "Glenn Fiddich",
    "C05" => "Nicolas Jaar",
    "D.." => "Flat Earth Society",
]);

而不是*你必须使用.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM