【问题标题】:preg_replace - array of individual replacementspreg_replace - 单个替换的数组
【发布时间】:2009-12-01 12:57:30
【问题描述】:

我正在努力实现以下目标:

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

干杯

【问题讨论】:

  • 我想我要输了 ;) 为什么你将 $subject 作为数组传递?
  • preg_replace 可以根据 $subject 的类型返回字符串或数组。

标签: php preg-replace


【解决方案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

我现在用你的例子对其进行了测试,修复了一些问题,现在它可以工作了(至少在那个例子中)。

【讨论】:

    【解决方案2】:
    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
    )
    

    【讨论】:

    • 这并不总是有效,因为在子字符串中替换不等于在完整字符串中替换。但这当然可以解决。这只是一个提示,说明您必须做什么才能使其正常工作。
    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 2021-12-20
    • 2013-08-01
    • 2016-08-14
    • 2017-12-21
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多