Preg_replace - 计数

时间:2014-06-15 00:55:34

标签: php count 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] ');

嗨,我写了那个剧本,我有一个小问题。我需要计算id的数量,应该是spoiler1,spoiler2等。

1 个答案:

答案 0 :(得分:1)

要使用PHP解决此问题,您可以使用preg_replace_callback代替。见这个缩短的例子:

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