PHP и Perl поддерживают замену «обратного вызова», что позволяет подключить некоторый код к генерации замены. Вот как вы можете сделать это в PHP с preg_replace_callback
class Placeholders{
private $count;
//constructor just sets up our placeholder counter
protected function __construct()
{
$this->count=0;
}
//this is the callback given to preg_replace_callback
protected function _doreplace($matches)
{
return '%'.$this->count++;
}
//this wraps it all up in one handy method - it instantiates
//an instance of this class to track the replacements, and
//passes the instance along with the required method to preg_replace_callback
public static function replace($str)
{
$replacer=new Placeholders;
return preg_replace_callback('/\[.*?\]/', array($replacer, '_doreplace'), $str);
}
}
//here's how we use it
echo Placeholders::replace("woo [yay] it [works]");
//outputs: woo %0 it %1
Вы можете сделать это с помощью глобального var и обычного обратного вызова функции, но оборачивать его в классе немного лучше.