How can preg_match be effectively used to set the active class in PHP menu navigation?

To set the active class in PHP menu navigation using preg_match, you can compare the current URL with each menu item's URL pattern using regular expressions. If there is a match, then you can add the active class to that menu item to highlight it as the active page.

<?php
$current_url = $_SERVER['REQUEST_URI'];

$menu_items = array(
    'Home' => '/',
    'About' => '/about',
    'Services' => '/services',
    'Contact' => '/contact'
);

foreach ($menu_items as $label => $url) {
    if (preg_match("~^$url~", $current_url)) {
        echo '<a href="' . $url . '" class="active">' . $label . '</a>';
    } else {
        echo '<a href="' . $url . '">' . $label . '</a>';
    }
}
?>