ありえないと思います。オプションの 4 番目のパラメーターで置換の制限を指定できますが、それは常に最初から始まります。
で探しているものを達成できる可能性がありますpreg_split()
。検索パターンのすべての場合に文字列を分割し、それらを 1 つずついじる必要があります。検索パターンが単純な文字列である場合は、 を使用して同じことを実現できますexplode()
。このアプローチを理解するのに助けが必要な場合は、喜んでお手伝いします。
編集:これがうまくいくかどうか見てみましょう:
$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);
注: これはまだテストされていません。動作するかどうかを報告してください。
編集2:
私は今あなたの例でそれをテストし、いくつかのことを修正しました、そしてそれは今(少なくともその例では)動作します。