正则表达式中的转义字符“\”(查找大括号之间的文本)

Escaping character "\" in regular expression (find text between curly brackets)

我目前的任务是转换字符串,并将“{}”之间的文本替换为里面提到的任何字符,

例如字符串:a{b|c}d{e|f}h,可能的结果:

'abdeh'
'abdfh'
'acdeh'
'acdfh'

此时我得到了一个函数

function producePatStr($str) {

    return preg_replace_callback('/{+(.*?)}/', function($matches) {

        $separated_chars = explode("|", $matches[1]);

        return $separated_chars[array_rand($separated_chars)]; 


    }, $str);

效果很好,但是你能帮我编辑我的正则表达式吗?如果它前面有转义字符“\”,你能帮我编辑一下 "ignore" 左括号吗,就像这样:

a{b|c}d\{e|f}h

结果应该是这样的: abd{e|f}h 或 acd{e|f}h

(?<!\){[^}]*}

您可以将 lookbehind 用于 same.See 演示。

https://regex101.com/r/fM9lY3/44

试试这个,应该适合你

function producePatStr($str) {
    return str_replace('\{', '{', preg_replace_callback('/[^\\]{([^}]*)}/', function($matches) {
        $separated_chars = explode("|", $matches[1]);
        return $separated_chars[array_rand($separated_chars)]; 
    }, $str)
    );
}

$text = 'a{b|c}d\{e|f}h';
$output = producePatStr($text);
var_dump($output);