PHP 使用 str_replace 替换多个值? [重复]

问题描述 投票:0回答:3

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

这是我替换前的 PHP 代码。

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

当我在

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

MontHours

当我在

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

HourSeconds

它返回这个值,我只想要

Month

php
3个回答
9
投票

##为什么不起作用?

这是一个替换陷阱,在 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;

如您所见,

m
被替换为
Month
h
中的
Month
被替换为
Hours
s
中的
Hours
被替换为
Seconds
。问题是,当您在
h
中替换
Month
时,无论字符串
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 = ['y', 'm', 'd', 'h', 'i', 's'];
$replace = ['Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds'];

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

6
投票

来自 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',
));

-1
投票

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

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

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

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