2009-12-01 36 views
2

我努力實現以下目標:的preg_replace - 個人替代的陣列

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

將返回所有replacments在同一個結果:

Array
(
[0] => 1 b 1
)

乾杯

+0

我覺得我失去了它;)爲什麼你究竟傳遞'$ subject'作爲一個數組? – Franz 2009-12-01 13:11:26

+0

preg_replace可以根據$ subject的類型返回一個字符串或一個數組。 – 2009-12-01 14:49:47

+0

我明白了。謝謝。 – Franz 2009-12-01 14:58:51

回答

1

我認爲這是不可能的。您可以在可選的第四個參數中指定替換限制,但始終從頭開始。

通過preg_split()可以實現您正在尋找的內容。你只需要在你的搜索模式的所有場合中分割你的字符串,然後一個接一個地混淆它們。如果你的搜索模式只是一個簡單的字符串,你可以用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

我現在跟你的例子進行了測試,修正了一些東西,現在(至少那個例子)的作品。

+0

這不適合你嗎? – Franz 2009-12-01 14:59:35

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 
) 
+0

這並不總是有效,因爲在子字符串中替換不等於在完整字符串中替換。但這當然可以解決。這只是一個暗示,你必須做些什麼才能讓它工作。 – 2009-12-01 13:47:08