How can regular expressions be utilized to extract and validate subdirectories in a URL using PHP?

Regular expressions can be utilized in PHP to extract and validate subdirectories in a URL by using the preg_match function to match the desired pattern. To extract subdirectories, we can use a regular expression pattern that matches the structure of a URL and captures the subdirectories. To validate the subdirectories, we can check if the extracted subdirectories match a predefined list of allowed subdirectories.

$url = "https://www.example.com/subdir1/subdir2/page";
$pattern = "/(?:https?:\/\/)?(?:www\.)?example\.com\/([a-zA-Z0-9_-]+)(?:\/([a-zA-Z0-9_-]+))+/";
if (preg_match($pattern, $url, $matches)) {
    $subdirectories = array_slice($matches, 1);
    
    $allowed_subdirectories = ['subdir1', 'subdir2'];
    foreach ($subdirectories as $subdir) {
        if (!in_array($subdir, $allowed_subdirectories)) {
            echo "Invalid subdirectory: $subdir";
        }
    }
} else {
    echo "URL does not match the expected pattern";
}