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";

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

而不是 * 你必须使用 .

你可以用 switch 来做,当然前提是它真的是最好的方法。很长的switch list很头疼...

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