从 preg_replace 中获取匹配项并将它们用作数组键

Get matches from a preg_replace and use them as an array key

我想从字符串中获取匹配项并在数组中使用它们作为键将字符串中的值更改为数组的值。

如果更容易实现的话,我可以把幻想标签改成%!也适用于 JS/jQuery 中没有问题的任何内容。此脚本用于外部 JS 文件并更改一些我无法从 JS/jQuery 访问的变量。所以我想用 PHP 插入它们并将它们缩小并压缩到浏览器。

$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';

$string = preg_replace('%!(.*?)!%',$array[],$string);
echo $string;

您可以使用 array_map with preg_quote to turn the keys of your array into regexes, and then use the values of the array as replacement strings in the array form of preg_replace:

$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';
$regexes = array_map(function ($k) { return "/" . preg_quote("%!$k!%") . "/"; }, array_keys($array));
$string = preg_replace($regexes, $array, $string);
echo $string;

输出:

This is just a Test String and i wanna Change the Variable

Demo on 3v4l.org