如何在不替换替换的子串的情况下替换多个子串?

时间:2017-06-04 14:31:07

标签: php string preg-replace str-replace strtr

帮助或协助以我的情况替换这些变体:

$string = "This is simple string";

$search = array (
  "This is simple",
  "string",
  "simple",
  "apple"
);

$replace = array (
  "This is red",
  "apple",
  "false",
  "lemon"
);

$result = str_replace($search, $replace, $string);
  

结果必须是:这是红苹果

     

不是这样:这是假苹果这是红柠檬这是假红柠檬

如果在每次更换时,更改的行被切割成某个变量,然后稍后返回,结果可能是正确的。但我不知道这是我的选择,但我无法实现。

1 个答案:

答案 0 :(得分:3)

使用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

重要

我必须告诉读者,这个美丽的功能也是一个古怪的功能。如果您以前从未使用过此功能,我建议您read the manual及其下方的评论。

对于这种情况很重要(相反,我的回答):

  

如果给出两个参数,则第二个应该是表单数组中的数组('from'=>'到',...)。返回值是一个字符串,其中所有出现的数组键都已被相应的值替换。 将首先尝试使用最长的密钥。更换子字符串后,将不再搜索其新值。

在OP的编码尝试中,键($search)按降序排序。这使功能行为与大多数人期望发生的事情保持一致。

但是,请考虑这个示例,其中键(及其值)稍微改变:

代码:(Demo

$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

相关问题