regexp in switch statement

后端 未结 3 1185
一向
一向 2020-12-03 00:56

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

相关标签:
3条回答
  • 2020-12-03 01:06

    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.

    0 讨论(0)
  • 2020-12-03 01:22

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

    0 讨论(0)
  • 2020-12-03 01:26

    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
    }
    
    0 讨论(0)
提交回复
热议问题