regexp in switch statement

2019-01-11 02:15发布

Are regex's allowed in PHP switch/case statements and how to use them ?

3条回答
萌系小妹纸
2楼-- · 2019-01-11 03:00

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
}
查看更多
Anthone
3楼-- · 2019-01-11 03:08

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.

查看更多
【Aperson】
4楼-- · 2019-01-11 03:12

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.)

查看更多
登录 后发表回答