如何替换最后一个HTML列表项?

时间:2015-03-31 12:24:13

标签: php html string

如何替换此字符串中的最后一个li元素?

在:

$var = 
   '<li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>';

后:

$var = 
   '<li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>
    <li class="foo">anything<li/>';

我尝试了preg_replace()

preg_replace('<li>', '<li class="foo">', $var);

但它不是预期的输出。如何更改代码以获得预期的输出?

2 个答案:

答案 0 :(得分:1)

这应该适合你:

(这里我只是将字符串拆分为一个带explode()的数组,然后我将最后一个元素和implode()再次替换为字符串.BTW:你关闭了li标签错了)

<?php

    $var = 
        '<li>anything</li>
        <li>anything</li>
        <li>anything</li>
        <li>anything</li>
        <li>anything</li>';

    $var = explode(PHP_EOL, $var);
    $var[count($var)-1] = preg_replace("/<li.*?>(.*?)<\/li>/", "<li class='foo'>$1</li>", $var[count($var)-1]);
    $var = implode(PHP_EOL, $var);

    print_r($var);

?>

输出:

<li>anything</li>
<li>anything</li>
<li>anything</li>
<li>anything</li>
<li class='foo'>anything</li>

答案 1 :(得分:1)

$var = 
   "<li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>
    <li>anything<li/>";
   $pos=strrpos($var,"<li>");
echo $final=substr_replace($var, '<li class="foo">anything<li/>',$pos);