views:

70

answers:

3

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

A: 

Yes.

 case (preg_match("/Mozilla( Firebird)?|phoenix/i", $browserName)?$browserName:!$browserName)

case preg_match("/$http(s)?/i", $uri, $matches): 

just a couple of examples.

Orbit
@Brandon: Thanks for your response. If i understand well, i can do `preg_match("/regex/", $foo) ? true : false;`. Can't I ?
M42
+1  A: 

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

nikic
@nikic: Thanks for your response. Then is it better (more readable) to do an if-elseif ?
M42
@M42: If you don't want to fall-through (by not `break`ing) you should use `if`. It's cleaner.
nikic
+1  A: 

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.

bourbaki
@bourbaki: Thanks a lot.
M42
This only works when `$name` evaluates to `true`. If `$name == ''` this will yield wrong results. -1
nikic
@nikic: you're right but this answers the OP's question : `Are regex's allowed in PHP switch/case statements and how to use them ?`
bourbaki