Skip to content
Advertisement

php switch statement with wildcard in the string

I would like to have a switch statement with both literal cases and cases with a wildcard in the string:

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

Of course the * will be taken literally here cause I define it as a string, so this does not work, but you know what I would like to accomplish: for the A, B and D cases the numbers can be whatever (*). Maybe with preg_match this is possible but that really blows my head. I Googled, I really did.

Advertisement

Answer

You can do it with switch, of course only, if it really best approach. Very long switch list of cases is a headache…

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!';}}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement