简体   繁体   中英

Why doesn't switch() support regex?

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;
}

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

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;
  }
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM