regexp in switch statement

Viewed 48721

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

4 Answers

Keep in mind the above answer can be slightly optimized like this:

Changing:

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

To:

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