preg_replace - Bireysel değiştirmeleri dizi

2 Cevap php

Ben aşağıdaki ulaşmak için çalışıyorum:

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

İstenilen sonuç:

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

Preg_replace ile bu ulaşmanın bir yolu var mı?

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

aynı sonucu tüm değiştireceğini dönecektir:

Array
(
[0] => 1 b 1
)

Şerefe

2 Cevap

Bunun mümkün olmadığını düşünüyorum. Sen isteğe bağlı dördüncü parametresi değiştirmeleri bir sınırı belirleyebilirsiniz, ama bu her zaman başında başlar.

Bu 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() ile aradığınızı elde etmek mümkün olabilir. Bu yaklaşımı bulmaktan yardıma ihtiyacınız varsa, ben yardımcı olmaktan mutluluk duyarız.

EDIT: Bu sizin için çalışıyor Bakalım:

$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);

Not: Bu henüz test edilmemiştir. Çalışıp çalışmadığını bildiriniz.

EDIT 2:

Ben şimdi, bir kaç şey sabit ve (en azından bu örnek ile) artık çalışıyor sizin örnek ile test edilmiştir.

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'));

Çıktı

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