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
2010-10-28 14:18:58
@Brandon: Thanks for your response. If i understand well, i can do `preg_match("/regex/", $foo) ? true : false;`. Can't I ?
M42
2010-10-28 15:23:54
+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
2010-10-28 14:49:54
+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
2010-10-28 18:26:52