字符串中带有通配符的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 这是可能的,但这真的让我大吃一惊。我谷歌了一下,我确实这么做了。


千巷猫影
浏览 83回答 3
3回答

忽然笑

当然,如果确实是最好的方法,您可以使用 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!';}}

明月笑刀无情

尝试这个 :$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";

Helenr

我写了一个函数。这是 withpreg_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",]);而不是*你必须使用.
打开App,查看更多内容
随时随地看视频慕课网APP