Add extra class for <li>
$string = '<ul>
<li id="34334" class="some_class"><a href="/stack/">Text</a></li>
<li id="someid" class="more_class"><a href="/overflow/">Text</a></li>
</ul>';
What I need (actually don't know how to do, please help):
- We must check
<a>
inside each<li>
- If
href
of<a>
==/stack/
, then add extra classcurrent
for parent<li>
Like, if we are searching for /stack/
, we should get this:
$string = '<ul>
<li id="34334" class="some_class current"><a href="/stack/">Text</a></li>
开发者_运维技巧 <li id="someid" class="more_class"><a href="/overflow/">Text</a></li>
<li id="34334" class="some_class current"><a href="/stack/">Text</a></li>
</ul>';
$string = '<ul>
<li class="some_class"><a href="/stack/">Text</a></li>
<li class="more_class"><a href="/overflow/">Text</a></li>
</ul>';
$new_string = preg_replace('/(<li( +id="[^"]*")? +class=")([^"]*)(" *>)( *<a +href="\/stack\/">)/', '$1$3 current$4$5', $string);
Note: Updated
Use jquery
$(document).ready(function(){
$('li > a[href*="stack"]').parent().addClass('newclass');});
精彩评论