php switch 语句中的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4043741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regexp in switch statement
提问by Toto
Are regex's allowed in PHP switch/case statements and how to use them ?
PHP switch/case 语句中是否允许使用正则表达式以及如何使用它们?
回答by
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.
Switch-case 语句的工作方式与 if-elseif 类似。
除了可以将 regex 用于 if-elseif 之外,您还可以在 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.
希望这可以帮助。
回答by Orbit
Yes, but you should use this technique to avoid issues when the switch argument evals to false
:
是的,但是您应该使用此技术来避免在 switch 参数 eval 为 时出现问题false
:
switch ($name) {
case preg_match('/John.*/', $name) ? $name : !$name:
// do stuff
}
回答by NikiC
No or only limited. You could for example switch for true
:
没有或只有有限。例如,您可以切换为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.)
这基本上为您提供了一个if-elseif-else
语句,但具有语法和可能switch
(例如失败。)