James
James

Reputation: 43647

Replace last class by php

$list = '<ul>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
</ul>';

How do I replace last <li>'s class from 'woman' to 'man'?

We should get finally:

$list = '<ul>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="man">photo</li>
</ul>';

Upvotes: 1

Views: 342

Answers (4)

Gordon
Gordon

Reputation: 316969

Couldn't find a suitable duplicate, so here is the DOM solution:

$list = '<ul>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
<li class="woman">photo</li>
</ul>';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXml($list);
$dom->documentElement->lastChild->setAttribute('class', 'man');
$dom->formatOutput = true;
echo $dom->saveXml($dom->documentElement);

http://codepad.org/6MVEytcp

If your markup is not XML compliant or if its a full html page consider using loadHTML to use libxml's HTML parser module. In that case, search around on StackOverflow or through my answers. There is plenty examples.

Upvotes: 1

fyr
fyr

Reputation: 20859

Two options:

  1. Use regular expressions and formulate the regular expression according to your needs. E.g. replace the last li blocks class attribute with a different value.

    $list = preg_replace('#^(.*<li class=")(.*)(">.*</li>.*)$#s', '$1man$3', $list);

  2. Generate a DOM-Tree from the fragment and use xpath to adress the last li element. (DOM - documentation

Upvotes: 2

danii
danii

Reputation: 5693

Try:

$off = strripos ( $list , "class=");
$list = substr_replace ( $list , "man" , $off+7, 5);

I think this is, by far, the simplest way to perform the trick, and no regexp needed at all!

Upvotes: 1

Steven Don
Steven Don

Reputation: 2431

With a regular expression (which is greedy by default), it is quite easy:

$list = preg_replace ('#^(.*class=")woman(".*)$#s', '$1man$2', $list);

That won't take into account that the class might be on something other than an LI tag or if the last LI tag has no class. To fix the first, you can simply change the regex:

$list = preg_replace ('#^(.*<li class=")woman(".*)$#s', '$1man$2', $list);

To fix the last:

$list = preg_replace ('#^(.*)<li[^>]*>(.*)$#s', '$1<li class="man">$2', $list);

Upvotes: 3

Related Questions