Huqe Dato
Huqe Dato

Reputation: 255

PHP router with switch statement and regular expressions not working

I have this code in php:

$route = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        switch ($route) {
            case '':
                echo "root";
                break;
            case '/':
                echo "root";
                break;
            case (preg_match("/^[a-zA-Z0-9-_]+$/", $route) ? true : false):
                echo "db";
                break;
            default:
                header("HTTP/1.0 404 Not Found");
                http_response_code(404);
                print(http_response_code());
                break;
        }

The regexp has to match all routes containing alphanumeric characters and - and _. But it doesn't, instead all slips to the default option, 404.

Probably it is something wrong with the pregmatch inside the switch. Please help.

Upvotes: 1

Views: 190

Answers (1)

Justinas
Justinas

Reputation: 43507

There are few issues:

  1. REQUEST_URI will return string with leading /, so you must add it in your regex: /^\/[a-zA-Z0-9-_]+$/
  2. switch checks if case value matches with provided value, so you should compare it with true instead of $route:
switch (true) {
    case $route == '':
        ...
    case $route == '/':
        ...
    case preg_match("/^\/[a-zA-Z0-9-_]+$/", $route):
        ...
}

But in that case it's better to use simple if conditions:


if (empty($route) || $route == '/') {
    echo 'root';
    return; // Use early return in order not to jump to other cases
}

if (preg_match("/^\/[a-zA-Z0-9-_]+$/", $route)) {
    echo 'db';
    return;
}


header("HTTP/1.0 404 Not Found");
http_response_code(404);
print(http_response_code());

Upvotes: 2

Related Questions