【问题标题】:PHP replace multiple value using str_replace? [duplicate]PHP使用str_replace替换多个值? [复制]
【发布时间】:2014-03-22 08:05:47
【问题描述】:

我需要使用 str_replace 替换多个值。

这是我的 PHP 代码替换。

$date = str_replace(
       array('y', 'm', 'd', 'h', 'i', 's'),
       array('Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds'),
       $key
    );

当我在$key 中传递m 时,它会返回类似的输出。

MontHours

当我在$key 中传递h 时,它会返回输出。

HourSeconds

它返回这个值,我只想要Month

【问题讨论】:

  • 向我们展示你是如何使用它的,看起来你在使用它之后再次使用它。即 m 变成了月,然后你再次运行它,月变成了月,因为月中的 h。
  • 或者它正在循环进行替换,而不是 100% 实现 str_replace,但是重新排列第一个数组中字母的顺序可能可以解决这个问题。

标签: php


【解决方案1】:

为什么它不起作用?

这是documentation for str_replace() 中提到的替换问题:

更换订单问题

因为str_replace() 从左到右替换,它可能会替换之前插入的值 多次替换。另请参阅本文档中的示例。

您的代码相当于:

$key = 'm';

$key = str_replace('y', 'Year', $key);
$key = str_replace('m', 'Month', $key);
$key = str_replace('d', 'Days', $key);
$key = str_replace('h', 'Hours', $key);
$key = str_replace('i', 'Munites', $key);
$key = str_replace('s', 'Seconds', $key);

echo $key;

如您所见,mMonth 替换,Month 中的hHours 替换,Hours 中的s 被替换为Seconds。问题是,当您在 Month 中替换 h 时,无论字符串 Month 代表最初的 Month 还是最初的 m,您都在这样做强>。每个str_replace() 都在丢弃一些信息——原始字符串是什么。

这就是你得到这个结果的方式:

0) y -> Year
Replacement: none

1) m -> Month
Replacement: m -> Month

2) d -> Days
Replacement: none

3) h -> Hours
Replacement: Month -> MontHours

4) i -> Munites
Replacement: none

5) s -> Seconds
Replacement: MontHours -> MontHourSeconds

解决办法

解决方案是使用strtr(),因为它不会更改已替换的字符。

$key = 'm';
$search = array('y', 'm', 'd', 'h', 'i', 's');
$replace = array('Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds');

$replacePairs = array_combine($search, $replace);
echo strtr($key, $replacePairs); // => Month

【讨论】:

    【解决方案2】:

    来自str_replace() 的手册页:

    注意

    更换订单问题

    因为 str_replace() 从左到右替换,所以在进行多次替换时,它可能会替换先前插入的值。另请参阅本文档中的示例。

    例如,将“m”替换为“Month”,然后将“Month”中的“h”替换为“Hours”,后者位于替换数组的后面。

    strtr() 没有这个问题,因为它同时尝试所有相同长度的键:

    $date = strtr($key, array(
        'y' => 'Year',
        'm' => 'Month',
        'd' => 'Days',
        'h' => 'Hours',
        'i' => 'Munites', // [sic]
        's' => 'Seconds',
    ));
    

    【讨论】:

      【解决方案3】:

      更简单的解决方法是更改​​搜索顺序:

      array('Year', 'Seconds', 'Hours', 'Month', 'Days', 'Minutes')
      

      str_replacepreg_replace 都会一次搜索每个搜索项。任何多值都需要确保订单不会更改以前的替换项目。

      【讨论】:

      • 不起作用。输入中的任何“s”都将替换为“SeconDayss”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 2012-01-03
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      相关资源
      最近更新 更多