使用以下命令,我可以匹配数组中的所有项,但只能替换所需的匹配值。有没有一种方法可以做到这一点,但不是直接替换,而是用指定的值包装匹配的文本?
当前代码:
$colours = array("Red", "Blue", "Green");
$string = "There are three Red and Green walls.";
echo str_replace($colours, "?", $string);
当前输出
There are three ? and ? walls.
通缉Ouput
There are three %1%Red%2% and %1%Green%2% walls.
根据是否要考虑上下文,解决方案会有所不同。
如果您计划只在任何上下文中按原样匹配字符串,并用%1%
和%2%
封装它们的副本重新封装,则需要使用
preg_replace("/" . implode("|", array_map(function($i) {return preg_quote($i, "/");}, $colours)) . "/", '%1%$0%2%', $string)
正则表达式在这里使用|
OR运算符形成,并且使用preg_quote
函数用转义
$colours
数组中项中的所有特殊字符。替换中的$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演示:
$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%.
我认为您可以使用array_map。这是我的例子:
$colors=数组("红色"、"蓝色"、"绿色"(;
$string=";有三堵红色和绿色的墙";
$func=函数($value(使用($colors({
return in_array($value, $colours) ? "%1%". $value ."%2%" : $value;
};
$text=array_map($func,分解(",$string((;
$text=内爆(",$text(;
echo$text;`
您想要的是preg_replace
。您可以将匹配项替换为包含匹配项的字符串。在这种情况下,"%1%$0%2%"
,其中$0
将被匹配替换。
但是,您需要引用(使用preg_quote
(并为数组的成员添加分隔符。我们可以用array_map
做到这一点。
这是代码:
echo preg_replace
(
array_map
(
function($input)
{
return "/".preg_quote($input, "/")."/";
},
$colours
),
"%1%$0%2%",
$string
);
不,我不建议假设它们在不引用的情况下使用是安全的,即使在这种情况下它们是安全的。是的,用它们创建一个正则表达式模式是可行的,但为什么要麻烦呢
最简单但不是最有效的:
$colours = array("Red", "Blue", "Green");
$colours_replacment = array('%1%Red%2%', '%1%Blue%2%', '%1%Green%2%');
$string = "There are three Red and Green walls.";
echo str_replace($colours, $colours_replacment, $string);
简单有效:
$colours = array("Red", "Blue", "Green");
$string = "There are three Red and Green walls.";
foreach($colours as $colour) {
$string = str_replace($colour, '%1%' . $colour . '%2%', $string);
}
echo $string;