PHP switch statement with preg_match

可紊 提交于 2019-12-02 03:28:42

问题


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 like:

If I run in my browser http://example.com/oop/page/view/1 its shows '404 page'. And when I run some address for example http://example.com/oop/page/view/test or even /oop/test its run 2nd case and dont know yet how. For sure something is wrong in my regex expresion..

public function check(){
    $url = filter_input(INPUT_GET, 'url');
    switch ($url) {
        case '':
            echo 'HomePage';
            break;
        case preg_match('#^/oop/page/view/\d+$#', $url):
            echo $url;
            break;
        default:
            echo '404 page';
            break;
    }

}

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/44317919/php-switch-statement-with-preg-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!