2009-12-01 43 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