Php 转义字符\&引用;在正则表达式中(在花括号中查找文本)
我当前的任务是转换字符串,并用其中提到的任何字符替换“{}”之间的文本 例如,字符串:a{b|c}d{e|f}h,以及可能的结果:Php 转义字符\&引用;在正则表达式中(在花括号中查找文本),php,regex,escaping,Php,Regex,Escaping,我当前的任务是转换字符串,并用其中提到的任何字符替换“{}”之间的文本 例如,字符串:a{b|c}d{e|f}h,以及可能的结果: 'abdeh' 'abdfh' 'acdeh' 'acdfh' 现在,我有一个函数 function producePatStr($str) { return preg_replace_callback('/{+(.*?)}/', function($matches) { $separated_chars = explode("|",
'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);
这很好,但是你能帮我编辑我的正则表达式吗?如果前面有转义字符“\”,请“忽略”开头的括号,就像这样:
a{b|c}d\{e|f}h
结果应该是:
abd{e|f}h或acd{e|f}h(?
(?<!\\){[^}]*}
您可以使用lookbehind
进行同样的操作。请参阅演示
试试这个,应该对你有用
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);
很抱歉提出了一个愚蠢的问题,但是如何在我的函数中使用这个正则表达式???简单替换会导致错误警告:preg_replace_callback():没有结尾匹配的分隔符“)”,在。。。。我的代码是:preg_replace_callback((?@user2858470$re=“/(?)?