tags:

views:

50

answers:

2
$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>';
+2  A: 
$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

Tim Cooper
doesn't work, if <li> has id=""
Happy
@Happy Can you be more specific and update your question?
Tim Cooper
@Tim Cooper, sorry, forgot about id. Question is updated.
Happy
works perfect now, thanks Tim!
Happy
+1  A: 

Use jquery

$(document).ready(function(){
$('li > a[href*="stack"]').parent().addClass('newclass');});
jsshah
need a php solution
Happy