PHP switch statement with preg_match

后端 未结 2 1192
礼貌的吻别
礼貌的吻别 2021-01-23 01:43

I have some problem to create a preg_match() inside my switch statement.

I want to write preg_match that match /oop/page/view/[some-number].

For now its working

相关标签:
2条回答
  • 2021-01-23 01:47

    What you should do instead is something like this:

    switch (true) {
      case preg_match(...):
    

    I don't remember if switch in PHP is strict or loose comparison, but if it's strict, just put a !! in front of each case to convert it to boolean.

    0 讨论(0)
  • 2021-01-23 01:50

    A switch statement compares each case expression to the original expression in the switch(). So

    case preg_match('#^/oop/page/view/\d+$#', $url):
    

    is analogous to:

    if ($url == preg_match('#^/oop/page/view/\d+$#', $url))
    

    This is clearly not what you want. If you want to test different kinds of expressions, don't use switch(), use if/elseif/else:

    if ($url == '') {
        echo 'Homepage';
    } elseif (preg_match('#^/oop/page/view/\d+$#', $url)) {
        echo $url;
    } else {
        echo '404 page';
    }
    
    0 讨论(0)
提交回复
热议问题