duanao4729 2017-06-04 14:31
浏览 34
已采纳

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

Help or assist as to replace in my case in such variants:

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

Result must be: This is red apple

Not so: This is false apple OR This is red lemon OR This is false red lemon

If, at each replacement, the changed line is cut into some variable and then returned later, the result may be correct. But I do not know this is my option, but I could not realize it.

  • 写回答

1条回答 默认 最新

  • dongyi9082 2017-06-04 15:32
    关注

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

    Output:

    This is red apple
    

    Important

    I must inform readers that this beautiful function is also a quirky one. If you've never used this function before, I recommend that you read the manual as well as the comments beneath it.

    Importantly for this case (rather, my answer):

    If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

    In the OP's coding attempt, the keys ($search) are ordered by descending length. This aligns the functions behavior with what most people would expect to happen.

    However, consider this demonstration where the keys (and their values) are shuffled around slightly:

    Code: (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));
    

    You may be surprised to know that this provides the same output: This is red apple

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看