1

帮助或协助在我的情况下替换此类变体:

$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);

结果必须是:这是红苹果

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

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

4

1 回答 1

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

重要的

我必须告诉读者,这个美丽的功能也是一个古怪的功能。如果您以前从未使用过此功能,我建议您阅读手册及其下方的注释。

重要的是对于这种情况(而不是我的回答):

如果给定两个参数,第二个应该是数组形式的数组('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

于 2017-06-04T15:32:12.300 回答