开发者

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):

  1. We must check <a> inside each <li>
  2. If href of <a> == /stack/, then add extra class current 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');});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜