2

私は次のことを達成しようとしています:

$subject = 'a b a';
$search = 'a';
$replace = '1';

望ましい結果:

Array
(
[0] => 1 b a
[1] => a b 1
)

preg_replace でこれを達成する方法はありますか?

preg_replace('/\b'.$search.'(?=\s+|$)/u', $replace, array($subject));

同じ結果ですべての置換を返します。

Array
(
[0] => 1 b 1
)

乾杯

4

2 に答える 2

1

ありえないと思います。オプションの 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

私は今あなたの例でそれをテストし、いくつかのことを修正しました、そしてそれは今(少なくともその例では)動作します。

于 2009-12-01T13:16:11.833 に答える
1
function multipleReplace($search,$subject,$replace) {
    preg_match_all($search, $subject,$matches,PREG_OFFSET_CAPTURE);
    foreach($matches as $match) {
    if (is_array($match)) {
        foreach ($match as $submatch) {
        list($string,$start) = $submatch;
        $length = strlen($string);
        $val = "";
        if ($start - 1 > 0) {
            $val .= substr($subject,0,$start);
        }
        $val .= preg_replace($search,$string,$replace);
        $val .= substr($subject,$start + $length);
        $ret[] = $val;
        }
    }
    }
    return $ret;
}

$search = 'a';

print_r(multipleReplace('/\b'.$search.'(?=\s+|$)/u','a b a','1'));

出力

Array
(
    [0] => 1 b a
    [1] => a b 1
)
于 2009-12-01T13:45:24.500 に答える