PHP使用str_replace替换多个值?
我需要使用str_replace替换多个值 这是我的PHP代码PHP使用str_replace替换多个值?,php,Php,我需要使用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
$date = str_replace(
array('y', 'm', 'd', 'h', 'i', 's'),
array('Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds'),
$key
);
当我在$key
中传递m
时,它将返回如下输出
MontHours
当我在$key
中传递h
时,它返回输出
HourSeconds
它返回这个值,我只想要月份
。为什么不工作?
这是一个替换的gotcha,在:
替换订单已收到
因为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;
如您所见,m
被替换为Month
,Month
中的h
被替换为Hours
中的s
被替换为Seconds
。问题是,当您在Month
中替换h
时,无论字符串Month
是表示最初的Month
还是最初的m
都是这样做的。每个str\u 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
解决方案
解决方案是使用,因为不会更改已替换的字符。
$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
从手册页中:
小心
替换订单已收到
因为str_replace()从左向右替换,所以在执行多次替换时,它可能会替换以前插入的值。另请参见本文档中的示例
例如,“m”替换为“Month”,然后“Month”中的“h”替换为“Hours”,后者在替换数组中出现
没有此问题,因为它会同时尝试相同长度的所有键:
$date = strtr($key, array(
'y' => 'Year',
'm' => 'Month',
'd' => 'Days',
'h' => 'Hours',
'i' => 'Munites', // [sic]
's' => 'Seconds',
));
一个更简单的修复方法是更改搜索顺序:
array('Year', 'Seconds', 'Hours', 'Month', 'Days', 'Minutes')
str_replace
和preg_replace
都将一次搜索一个搜索项。任何多值都需要确保订单不会更改以前的替换项 让我们看看你是如何使用它的,就像你在使用后再次使用它一样。。ie m变为month,然后您再次运行它month变为Monthhours,因为h在month中。或者它循环执行替换,而不是100%执行str_replace,但是重新排列第一个数组中字母的顺序可能可以解决此问题。不起作用。输入中的任何“s”都将替换为“SeconDayss”。