PHP 使用 str_replace 替换多个值?

标签 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

它返回这个值我只想要 Month

最佳答案

为什么不起作用?

这是 documentation for str_replace() 中提到的一个替换陷阱:

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

你的代码等同于:

$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 被替换为 HoursHours 中的 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

关于PHP 使用 str_replace 替换多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22575094/

相关文章:

javascript - 计数超过限制后如何添加类

php - Goutte-dom爬虫-移除节点

php - 有没有更有效的方法来做到这一点

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 另一个类中的 MySQLi 连接

php - 使用哪个 : REMOTE_ADDR or SERVER_ADDR

PHP GD : How to get imagedata as binary string?

php - 删除长词正则表达式

php - 在 laravel 4 中生成相对于基本 url 的 url

php - DOMXPath - 获取节点