PHP switch/case 语句中是否允许正则表达式以及如何使用它们?
Switch-case 语句像 if-elseif 一样工作。
除了可以将正则表达式用于 if-elseif 之外,您还可以在 switch-case 中使用它。
if (preg_match('/John.*/', $name)) {
// do stuff for people whose name is John, Johnny, ...
}
可以编码为:
switch $name {
case (preg_match('/John.*/', $name) ? true : false) :
// do stuff for people whose name is John, Johnny, ...
break;
}
没有或只有有限的。例如,您可以切换为
true
:
switch (true) {
case $a == 'A':
break;
case preg_match('~~', $a):
break;
}
这基本上给了你一个
if
-elseif
-else
语句链,但是具有switch
的语法和可能(例如fall-through。)
是的,但是当 switch 参数计算为
false
: 时,您应该使用这种技术来避免出现问题
switch ($name) {
case preg_match('/John.*/', $name) ? $name : !$name:
// do stuff
}
记住上面的答案可以像这样稍微优化一下:
变化:
switch $name {
case (preg_match('/John.*/', $name) ? true : false) :
// do stuff for people whose name is John, Johnny, ...
break;
}
致:
switch $name {
case (bool)preg_match('/John.*/', $name) :
// do stuff for people whose name is John, Johnny, ...
break;
}