switch 语句中的正则表达式

问题描述 投票:0回答:4

PHP switch/case 语句中是否允许正则表达式以及如何使用它们?

php switch-statement
4个回答
144
投票

Switch-case 语句像 if-elseif 一样工作。
除了可以将正则表达式用于 if-elseif 之外,您还可以在 switch-case 中使用它。

if (preg_match('/John.*/', $name)) {
    // do stuff for people whose name is John, Johnny, ...
}

可以编码为:

switch $name {
    case (preg_match('/John.*/', $name) ? true : false) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}

20
投票

没有或只有有限的。例如,您可以切换为

true

switch (true) {
    case $a == 'A':
        break;
    case preg_match('~~', $a):
        break;
}

这基本上给了你一个

if
-
elseif
-
else
语句链,但是具有
switch
的语法和可能(例如fall-through。)


17
投票

是的,但是当 switch 参数计算为

false
:

时,您应该使用这种技术来避免出现问题
switch ($name) {
  case preg_match('/John.*/', $name) ? $name : !$name:
    // do stuff
}

4
投票

记住上面的答案可以像这样稍微优化一下:

变化:

switch $name {
    case (preg_match('/John.*/', $name) ? true : false) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}

致:

switch $name {
    case (bool)preg_match('/John.*/', $name) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}
© www.soinside.com 2019 - 2024. All rights reserved.