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

我认为这是不可能的。您可以在可选的第四个参数中指定替换限制,但始终从开头开始。

可以通过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

我现在用你的例子测试了它,修复了一些东西,它现在可以工作了(至少在那个例子中)。

于 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 回答