How can PHP developers optimize their code to handle different URL structures, such as including language, category, and subcategory parameters?

PHP developers can optimize their code by using a routing system that parses the URL and extracts the necessary parameters like language, category, and subcategory. This can be achieved by defining routes in a centralized configuration file and using regular expressions to match the URL patterns. By implementing a flexible routing system, developers can easily handle different URL structures and extract the required parameters for processing.

// Define routes in a configuration file
$routes = [
    '/{lang}/{category}/{subcategory}' => 'handleRequest',
];

// Parse the URL and extract parameters
$requestUri = $_SERVER['REQUEST_URI'];
foreach ($routes as $pattern => $handler) {
    if (preg_match('#^' . $pattern . '$#', $requestUri, $matches)) {
        array_shift($matches); // Remove the full match
        call_user_func_array($handler, $matches);
        break;
    }
}

// Handle the request based on extracted parameters
function handleRequest($lang, $category, $subcategory) {
    // Process the request using the extracted parameters
    echo "Language: $lang, Category: $category, Subcategory: $subcategory";
}