I think it is not possible. You can specify a limit of replacements in the optional fourth parameter, but that always starts at the beginning.
It could be possible to achieve what you're looking for with preg_split()
. You would just have to split your string on all occasions of your search pattern and then mess with them one by one. If your search pattern is just a simple string, you can achieve the same with explode()
. If you need help figuring this approach out, I'll be happy to help.
EDIT: Let's see if this works for you:
$subject = 'a b a';
$pattern = '/a/';
$replace = 1;
// We split the string up on all of its matches and obtain the matches, too
$parts = preg_split($pattern, $subject);
preg_match_all($pattern, $subject, $matches);
$numParts = count($parts);
$results = array();
for ($i = 1; $i < $numParts; $i++)
{
// We're modifying a copy of the parts every time
$partsCopy = $parts;
// First, replace one of the matches
$partsCopy[$i] = $replace.$partsCopy[$i];
// Prepend the matching string to those parts that are not supposed to be replaced yet
foreach ($partsCopy as $index => &$value)
{
if ($index != $i && $index != 0)
$value = $matches[0][$index - 1].$value;
}
// Bring it all back together now
$results[] = implode('', $partsCopy);
}
print_r($results);
Note: This is not tested yet. Please report whether it works.
EDIT 2:
I tested it with your example now, fixed a few things and it works now (at least with that example).