preg_replace 一次替换多个模式

mmo*_*nem 3 php regex preg-replace preg-replace-callback

我在 $subject 上应用的替换很少,但我不想让旧替换 #(1 .. i-1) 的输出与当前替换 #i 匹配。

$subject1 = preg_replace($pat0, $rep0, $subject0);
$subject2 = preg_replace($pat1, $rep1, $subject1);
$subject3 = preg_replace($pat2, $rep2, $subject2);
Run Code Online (Sandbox Code Playgroud)

我尝试将一个preg_replace与数组用于模式和替换,希望它能够立即实现;但结果证明只是连续调用简单的preg_replace(当然有一些优化)

在我阅读了preg_replace_callback 之后,我想这不是一个解决方案。

有什么帮助吗?

Qta*_*tax 5

使用回调,您可以通过使用捕获组来检测(?:(patternt1)|(pattern2)|(etc)匹配的模式,例如,只会定义匹配模式的捕获组。

唯一的问题是您当前的捕获组将被转移。要修复(阅读解决方法),您可以使用命名组。(分支重置(?|(foo)|(bar))会起作用(如果您的版本支持),但是您必须使用其他方式检测哪个模式匹配。)

例子

function replace_callback($matches){
    if(isset($matches["m1"])){
        return "foo";
    }
    if(isset($matches["m2"])){
        return "bar";
    }
    if(isset($matches["m3"])){
        return "baz";
    }
    return "something is wrong ;)";
}

$re = "/(?|(?:regex1)(?<m1>)|(?:reg(\\s*)ex|2)(?<m2>)|(?:(back refs) work as intended \\1)(?<m3>))/";

$rep_string = preg_replace_callback($re, "replace_callback", $string);
Run Code Online (Sandbox Code Playgroud)

没有经过测试(这里没有 PHP),但是这样的东西可以工作。