3 回答
TA贡献1806条经验 获得超5个赞
当然,如果确实是最好的方法,您可以使用 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!';}}
TA贡献1828条经验 获得超4个赞
尝试这个 :
$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";
TA贡献1780条经验 获得超3个赞
我写了一个函数。这是 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",
]);
而不是*你必须使用.
- 3 回答
- 0 关注
- 143 浏览
添加回答
举报