Menús dinámicos con PHP en 2 minutos

Siempre me he liado más de la cuenta para crear menús dinámicos que se auto marquen cuando el usuario entra en cada una de las secciones de los mismos. Funciones con miles de parámetros, líos de variables… todo eso se ha acabado con el siguiente tip.

Primero definimos el menú (en este caso de forma estática, pero se podría hacer a través de bases de datos o de un include) en una lista simple (ul y li):

<?php
# Pop your code, one link per line, into the $menu variable
$menu = <<<MENU
<ul id="nav">
    <li><a href="/" title="Where the heart is">Home</a></li>
    <li><a href="/archives/" title="Things that have passed.">Archives</a></li>
    <li><a href="/about/" title="All about Matt">About</a></li>
    <li><a href="/photos/" title="It's the 'photo' in Matt">Photos</a></li>
    <li><a href="/music/" title="The food of love">Music</a></li>
    <li><a href="/scripts/" title="Free (as in beer and speech) code">Scripts</a></li>
    <li><a href="/jazzquotes/" title="Great quotes from amazing musicians. More in the future.">Jazz Quotes</a></li>
    <li><a href="/xml/" title="Syndicate the content here. Get Matt to-go.">Syndicate</a></li>
    <li><a href="/contact/" title="Contact.">Contact</a></li>
</ul>
MENU;

Ahora el truco, evaluar la variable $_SERVER[REQUEST_URI] con una expresión regular a ver si coincide con el href de arriba. Siendo así marcamos como id=“current” la opción. El resto lo hace el CSS:

<?php
$lines = split("\n", $menu);
foreach ($lines as $line) {
    $current = false;
    preg_match('/href="([^"]+)"/', $line, $url);
    if (substr($_SERVER["REQUEST_URI"], 0, 5) == substr($url[1], 0, 5)) {
        $line = str_replace('<a h', '<a id="current" h', $line);
        }
    echo $line."\n";
}
?>