【问题标题】:How to do replace multiple times ? php多次更换怎么办? php
【发布时间】:2015-09-03 19:26:01
【问题描述】:

对于这个字符串,我想用word2word2 替换word1word1

word1 word2

这是我想做的:

1.用 word2 替换 word1 => 我得到:word2 word2

2.用 word1 替换 word2 => 我应该得到 word2 word1。

但我明白了: word1 word1 因为 str_replace 函数也替换了第一个替换的 word1。

如何避免此类问题?

谢谢

【问题讨论】:

  • 使用strtr() 而不是str_replace()
  • 你为什么不explode()你的字符串并切换单词?
  • @MarkBaker 谢谢你的回答。
  • @Daan 你能写下你的答案吗,我不明白你的解决方案。谢谢
  • @david 检查答案。

标签: php string replace str-replace php-5.3


【解决方案1】:

您无法通过 str_replace 实现此目的。使用旨在这样做的字符串翻译(strtr):

$words = 'word1 word2';
$wordsReplaced = strtr($words, [
    'word1' => 'word2',
    'word2' => 'word1'
]);

【讨论】:

  • 感谢您的回答,但您认为 strtr 对长字符串有效吗? 500 个字符,20 个替换?
  • 好吧,str_replace 大约快两倍,但另一方面,500 个字符并不是什么大问题。而你宁愿在这里没有选择。我在高性能广告服务应用中使用 strtr 并且效果很好。
猜你喜欢
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2014-03-03
  • 2011-06-02
  • 2012-11-26
  • 2011-07-22
相关资源
最近更新 更多