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

问题描述 投票:0回答: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);

结果必须是:这是红苹果

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

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

php string preg-replace str-replace strtr
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

重要

我必须告诉读者,这个漂亮的功能也是一个古怪的功能。如果你以前从未使用过这个功能,我建议你阅读手册以及它下面的评论。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.