使用strtr()
:
$string = "This is simple string";
$search = array
(
"This is simple",
"string",
"simple",
"apple"
);
$replace = array
(
"This is red",
"apple",
"false",
"lemon"
);
echo strtr($string,array_combine($search, $replace));
输出:
This is red apple
重要的
我必须告诉读者,这个美丽的功能也是一个古怪的功能。如果您以前从未使用过此功能,我建议您阅读手册及其下方的注释。
重要的是对于这种情况(而不是我的回答):
如果给定两个参数,第二个应该是数组形式的数组('from' => 'to', ...)。返回值是一个字符串,其中所有出现的数组键都已替换为相应的值。最长的键将首先被尝试。一旦子字符串被替换,它的新值将不会被再次搜索。
在 OP 的编码尝试中,键 ( $search
) 按长度降序排列。这使函数行为与大多数人期望发生的情况保持一致。
但是,考虑一下这个演示,其中键(及其值)被稍微打乱:
代码:(演示)
$string="This is simple string";
$search=[
"string", // listed first, translated second, changed to "apple" which becomes "untouchable"
"apple", // this never gets a chance
"simple", // this never gets a chance
"This is simple" // listed last, but translated first and becomes "untouchable"
];
$replace=[
"apple",
"lemon",
"false",
"This is red"
];
echo strtr($string,array_combine($search, $replace));
您可能会惊讶地发现这提供了相同的输出:This is red apple