简体   繁体   English

PHP preg_replace使用发现的表达式作为键的可变值

[英]PHP preg_replace with variable value using found expression as key

I have a string $src with two variable placeholders %%itemA%% and %%itemB%% . 我有一个带有两个可变占位符%%itemA%%%%itemB%%的字符串$src The idea is for the regular expression to match any term listed ITEMA|ITEMB|ITEMC , case insensitively, and replace the term with the value of the array item using the term as the array key. 这个想法是让正则表达式不区分大小写地匹配ITEMA|ITEMB|ITEMC列出的任何术语,并使用该术语作为数组关键字将其替换为数组项的值。

$replacements = [
    'itemA' => 'replacedItemA',
    'itemB' => 'replacedItemB',
    'itemC' => 'replacedItemC'
];

$src = "A B C %%itemA%% D E F %%itemB%% G H I";

$src = preg_replace('/\%\%(ITEMA|ITEMB|ITEMC)%%/i', $replacements['\1'], $src);

echo $src;

In this example the expected result is for %%itemA%% to be replaced with $replacements['itemA'] 's value and %%itemB%% to be replaced with $replacements['itemB'] 's value 在此示例中,预期结果是将%%itemA%%替换为$replacements['itemA']的值,并将%%itemB%%替换为$replacements['itemB']的值

Expected output from the echo was echo预期输出为

ABC replacedItemA DEF replacedItemB GHI ABC替换项目A DEF替换项目B GHI

Actual output, oddly, simply replaced the found terms with nothing (note the double spaces where the variable was removed) 奇怪的是,实际输出只是简单地将发现的条件替换为什么(注意删除了变量的双空格)

ABCDEFGHI

Why is the term's string not being used in the $replacements['key'] to use the value of the array variable? 为什么在$replacements['key']不使用术语的字符串来使用数组变量的值?

Your approach is wrong. 您的方法是错误的。 Since you are dealing with literal strings, you can avoid the regex and use a faster way: 由于您正在处理文字字符串,因此可以避免使用正则表达式并使用更快的方法:

$replacements = [
    '%%itemA%%' => 'replacedItemA',
    '%%itemB%%' => 'replacedItemB',
    '%%itemC%%' => 'replacedItemC'
];

$str = strtr($str, $replacements);

You just need to replace the preg_replace with preg_replace_callback like this: 你只需要更换preg_replacepreg_replace_callback是这样的:

$src = preg_replace_callback('/%%(ITEM[ABC])%%/i', function ($m) use ($replacements) {
 return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
}
, $src);

See IDEONE demo IDEONE演示

The issue is that \\1 backreference can only be used inside the pattern to refer to the text captured with the first capturing group or inside a replacement pattern, but only as a literal part of it. 问题是\\1反向引用只能在模式内部用于引用第一个捕获组捕获的文本或在替换模式内部,但只能用作其文字部分。 The \\1 is not automatically evaluated to be used as an argument. \\1不会自动求值以用作参数。

I also contracted the pattern a bit, but I guess it is just a sample. 我也缩小了模式,但我猜只是一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM