根据您是否要考虑上下文,解决方案会有所不同。
如果您打算在任何上下文中按原样匹配字符串并用%1% 和%2% 随附的副本替换,则需要使用
preg_replace("/" . implode("|", array_map(function($i) {return preg_quote($i, "/");}, $colours)) . "/", '%1%$0%2%', $string)
这里使用| OR 运算符形成正则表达式,$colours 数组中的项目中的所有特殊字符都使用\ 使用preg_quote 函数进行转义。替换中的$0 指的是整个匹配值。
如果$colours 是带有空格的短语,您需要对项目进行排序,以便较长的字符串在前:
rsort($colours, SORT_FLAG_CASE | SORT_STRING);
echo "\n" . preg_replace("/" . implode("|", array_map(function($i) {return preg_quote($i, "/");}, $colours)) . "/", '%1%$0%2%',$string);
如果这些$colours是简单的英文字母单词,并且你想将它们作为整个单词匹配,你不需要preg_quote,你可以使用单词边界,比如:
preg_replace("/\b(?:" . implode('|', $colours) . ")\b/", '%1%$0%2%', $string)
要使搜索不区分大小写,请在 preg_replace 第一个参数的最后一个 / 正则表达式分隔符之后添加 i 标志。
见PHP demo:
$colours = array("Red", "Blue", "Green");
$string = "There are three Red and Green walls.";
echo preg_replace("/" . implode("|", array_map(function($i) {return preg_quote($i, "/");}, $colours)) . "/", '%1%$0%2%', $string);
// => There are three %1%Red%2% and %1%Green%2% walls.
echo "\n" . preg_replace("/\b(?:" . implode('|', $colours) . ")\b/", '%1%$0%2%', $string);
// => There are three %1%Red%2% and %1%Green%2% walls.
$colours = array("Red", "Blue", "Green", "Blue jeans");
$string = "There are three Red and Green walls and Blue jeans.";
rsort($colours, SORT_FLAG_CASE | SORT_STRING);
echo "\n" . preg_replace("/" . implode("|", array_map(function($i) {return preg_quote($i, "/");}, $colours)) . "/", '%1%$0%2%',$string);
// => There are three %1%Red%2% and %1%Green%2% walls and %1%Blue jeans%2%.