Search code examples
phppreg-replaceincrement

Make replacements in a string and use an incremented value in each replacement


$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] ');

I need to increment the number of the id to be spoiler1, spoiler2 etc. for each replacement.


Solution

  • 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;
    }