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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:48:22  来源:igfitidea点击:

regexp in switch statement

phpswitch-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-elsestatement, but with syntax and might of switch(for example fall-through.)

这基本上为您提供了一个if-elseif-else语句,但具有语法和可能switch(例如失败。)