$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等。
答案 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;
}