dtt83024 2017-02-20 10:55
浏览 102
已采纳

str_replace()有3个不同的替换

I have this PHP Code for add a specific class to <a> element in a WordPress menú, before to clean all other elements from WordPress:

<?php 

$menuParameters = array(
  'menu' => '40',
  'container'       => false,
  'echo'            => false,
  'items_wrap'      => '%3$s',
  'depth'           => 0,
);

$menu = strip_tags(wp_nav_menu( $menuParameters ), '<a>' );

$find = array('<a');
$replace = array('<a class="pro-link pro1"');
echo str_replace( $find, $replace, $menu );

?>

This print some like this:

<a class="pro-link pro1" href="link1">Link1</a>
<a class="pro-link pro1" href="link2">Link2</a>
<a class="pro-link pro1" href="link3">Link3</a>

The problem is that I need to put 3 distinct classes (pro1, pro2 and pro3), and print like this:

<a class="pro-link pro1" href="link1">Link1</a>
<a class="pro-link pro2" href="link2">Link2</a>
<a class="pro-link pro3" href="link3">Link3</a>

How I can do it? I need to iterate?

Thanks for your help! :)

UPDATE:

It's working but the first item print only "pro", and the next "pro1", "pro2". I tried to change value of $replacecounter but it doesn't work. I need just solve that and will work perfect.

<?php 

$menuParameters = array(
  'menu' => '40',
  'container'       => false,
  'echo'            => false,
  'items_wrap'      => '%3$s',
  'depth'           => 0,
);

$replacecounter = 1;      

$menu = strip_tags(wp_nav_menu( $menuParameters ), '<a>' );                                                 

echo preg_replace_callback('/<a/', 'replaceCounter', $menu);

function replaceCounter() {
    global $replacecounter;
    $str="pro-link pro". $replacecounter++;
    return "<a class='$str'";
}

?>
  • 写回答

2条回答 默认 最新

  • douchan0523 2017-02-20 11:43
    关注

    You can try this:Thread using preg_replace_callback.On each match replaceCounter will be called and replaced value is returned.

    $replacecounter = 1;
    $str='<a  href="link1">Link1</a>
    <a  href="link2">Link2</a>
    <a  href="link3">Link3</a>';
    echo preg_replace_callback('/<a/', 'replaceCounter', $str);
    
    function replaceCounter() {
        global $replacecounter;
        $str="pro-link pro". $replacecounter++;
        return "<a class='$str'";
    }
    

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料