dsc6517 2014-06-15 00:55
浏览 22
已采纳

Preg_replace - 计数

 $pattern = array ('/\[spoiler\]/', "/\[.spoiler\]/");

 $replace = array ("<button title=\"Click to show/hide content\" type=\"button\" onclick=\"if(document.getElementById('spoiler') .style.display=='none') {document.getElementById('spoiler') .style.display=''}else{document.getElementById('spoiler') .style.display='none'}\">Pokaż/ukryj</button><div id=\"spoiler\" style=\"display: none;\">", "</div>");

 <?php echo preg_replace($pattern, $replace, '[spoiler]awdawdawd[/spoiler] ');

Hi, i wrote that script and i have one little problem. I need to count the number of id, that should be spoiler1, spoiler2 etc.

  • 写回答

1条回答 默认 最新

  • duangang2825 2014-06-15 07:20
    关注

    To solve this with PHP you can use preg_replace_callback instead. See this shortened example:

    $counter  = 1;
    $replaced = preg_replace_callback('/\[spoiler\]/', 'replace_with_count', '[spoiler]awdawdawd another[spoiler]');
    echo $replaced;
    # will show: <button id='spoiler1'>Show 1</button>awdawdawd another<button id='spoiler2'>Show 2</button>
    
    /**
     * Replace all occurrence with an incrementing number
     *
     * @param array $matches
     * @return string
     */
    function replace_with_count($matches) {
        global $counter;
        $result = "<button id='spoiler{$counter}'>Show {$counter}</button>";
        $counter++;
    
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图