Correct solution to the problem
function incremental_replace($subject) {
$replacer = function($matches) {
$index = 0;
return preg_replace('/\?/e', '++$index', $matches[0]);
};
return preg_replace_callback('/\[[^\]]*\]/', $replacer, $subject);
}
$subject = "Replace ? question mark in brackets [? with ? incre?mental ??]?...";
echo incremental_replace($subject);
Previous form of this answer
I had misunderstood the question, and answered another similar question instead. I 'm leaving the answer here because someone might find it useful.
The general idea is this:
function replacer($matches) {
$replacements = array(1, 2, 34);
$index = 0;
return preg_replace('/\?+/e', '$replacements[$index++]', $matches[0]);
}
$subject = "Replace ? question mark in brackets [? with ? incremental ??]?...";
echo preg_replace_callback('/\[[^\]]*\]/', 'replacer', $subject);
See the basic concept in action.
If you are using PHP >= 5.3, you can then do a much more generalized solution:
function incremental_replace($subject, $replacements) {
$replacer = function($matches) use ($replacements) {
$index = 0;
return preg_replace('/\?+/e', '$replacements[$index++]', $matches[0]);
};
return preg_replace_callback('/\[[^\]]*\]/', $replacer, $subject);
}
$subject = "Replace ? question mark in brackets [? with ? incremental ??]?...";
echo incremental_replace($subject, array(1, 2, 34));
Finally, if you are willing to limit yourself to only single question marks (i.e. if the ?? inside the brackets can be changed to simply ?) then you can swap the preg_replace inside the "replacer" function with a simple str_replace, which would be faster.