There is a navigation block:

<ul class="nav navbar-nav"> <li> <a class="text-mutten" href="/link1">Пункт 1</a> </li> <li class='test other-cls'> <a href="/link2">Пункт 2</a> </li> <li> <a href="/link3">Пункт 3</a> </li> <li class=""> <a class="text-mutten active" href="/link4">Пункт 4</a> </li> </ul> 

And given the defining parameter insertion by href . for example, param = 'link2'

The regular expression should see in which href there is an occurrence of 'link2'. And where it was found, add the class "active" to the "LI" of the parent.

those. in our example, li class = 'test other-cls' will turn into class = 'test other-cls active'

How gracefully to implement it?

    1 answer 1

    Solved the problem itself. It is unlikely that anyone will come in handy and am not sure that the solution is normal, but still

    $ block is our navigation block; $ param - what we are looking for.

     $block = preg_replace_callback("/\<li(.*?)class=(.*?)(active)(.*?)\>/sui", function ($match) { $cl = trim($match[2]) . trim($match[4]); return '<li' . $match[1] . (!empty($cl) ? 'class=' . $cl : '') . '>'; }, $block); if (preg_match_all("/\<li(.*?)href=[\"|'](.*?)[\"|'](.*?)li\>/sui", $block, $matchs)) { $i = -1; foreach ($matchs[2] as $key => $match) { if (strpos($match, $param) !== false) { $i = $key; break; } } if ($i >= 0) { if (strpos($matchs[0][$i], 'class') !== false) { $matchs[0][$i] = preg_replace("/class=([\"|'])/sui", 'class=$1active ', $matchs[0][$i]); } else { $matchs[0][$i] = preg_replace("/\<li/sui", '<li class="active"', $matchs[0][$i]); } } $block = implode($matchs[0], ''); } 
    • If you have one static page then all the rules. And if this is a page from a third-party service, then it is better to alter this code using a domdocument. Because regulars are very poorly combined with html / xml code. - fens