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>';
}
}
?>
Keywords
Related Questions
- Are there any best practices for efficiently extracting plaintext or quoted-printable content from emails in PHP?
- In what ways can experienced PHP developers provide constructive feedback and guidance to beginners in online forums without causing frustration or discouragement?
- How can PHP developers ensure the security and reliability of file reading operations when accessing files from remote domains?