Reputation: 12588
My understanding of switch()
is that it avoids repeating the string.
If so, why doesn't it support regex, like the below code? Or am I missing the point of switch()
?
switch($username){
case "":
array_push($errors, "Username cannot be blank");
break;
case "admin":
array_push($errors, "Username cannot be 'admin'");
break;
case regex_switch('/xxx.*/'):
array_push($errors, "Username cannot begin 'xxx'");
break;
}
Upvotes: 0
Views: 97
Reputation: 91488
You could do something like:
switch $username {
case "":
array_push($errors, "Username cannot be blank");
break;
case "admin":
array_push($errors, "Username cannot be 'admin'");
break;
case (preg_match('/^xxx.*/', $username) ? true : false) :
array_push($errors, "Username cannot begin 'xxx'");
break;
}
Upvotes: 0
Reputation: 32272
Because it doesn't. End of story.
The lesson is that you need to think up a way around this constraint rather than petitioning the PHP devs to implement some esoteric feature and getting no work done in the process.
Why not:
$disallowed_usernames = array(
array('/^$/', 'be blank'),
array('/^admin/', 'begin with "admin"'),
array('/^xxx/', 'begin with "xxx"'),
);
foreach( $disallowed_usernames as $item ) {
if( preg_match($item[0], $username) ) {
array_push($errors, 'Username cannot ' . $item[1]);
break;
}
}
Upvotes: 0
Reputation: 674
switch isn't a general conditional statement, but rather compares values. Think of it as expanding to a series of if statements.
For instance, think of the following (pseudo-code):
switch(a) {
case x: ... break;
case y: ... break;
case z: ... break;
}
As expanding to something like:
if (a == x) {
}
elseif (a == y) {
}
elseif (a == z) {
}
So a regex in one of your cases, ends up being:
if (a == regex_switch(...)) {
}
Where a is a string...
Upvotes: 5