PHP and Perl both support a 'callback' replacement, allowing you to hook some code into generating the replacement. Here's how you might do it in PHP with 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
You could do this with a global var and a regular function callback, but wrapping it up in class is a little neater.