Are regex's allowed in PHP switch/case statements and how to use them ?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Switch-case statement works like if-elseif.
As well as you can use regex for if-elseif, you can also use it in switch-case.
if (preg_match('/John.*/', $name)) {
// do stuff for people whose name is John, Johnny, ...
}
can be coded as
switch $name {
case (preg_match('/John.*/', $name) ? true : false) :
// do stuff for people whose name is John, Johnny, ...
break;
}
Hope this helps.
回答2:
No or only limited. You could for example switch for true
:
switch (true) {
case $a == 'A':
break;
case preg_match('~~', $a);
break;
}
This basically gives you an if-elseif-else
statement, but with syntax and might of switch
(for example fall-through.)
回答3:
Yes, but you should use this technique to avoid issues when the switch argument evals to false
:
switch ($name) {
case preg_match('/John.*/', $name) ? $name : !$name:
// do stuff
}