开发者

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>';


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


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


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!


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜