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

问题描述

我希望有一个 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可以实现,但这确实让我震惊。我用Google搜索,确实做到了。

解决方法

尝试一下:

$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,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!';}}
,

我写了一个函数。 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",]);

您必须使用*来代替.