str_replace 数组 [英] str_replace with array

查看:52
本文介绍了str_replace 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用数组时遇到了 PHP 函数 str_replace 的一些问题.

I'm having some troubles with the PHP function str_replace when using arrays.

我收到这条消息:

$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");

我正在尝试像这样使用 str_replace:

And I am trying to use str_replace like this:

$new_message = str_replace(
    array('l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'),
    array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),
    $message);

结果应该是在魔鬼座位上的主教宿舍的好玻璃,但相反,我得到了p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.

The result should be A good glass in the bishop's hostel in the devil's seat, but instead, I get p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.

但是,当我只尝试替换 2 个字母时,它会很好地替换它们:

However, when I only try replacing 2 letters it replaces them well:

$new_message = str_replace(array('l','p'), array('a','e'), $message);

字母 lp 将被 ae 替换.

the letters l and p will be replaced by a and e.

如果它们的大小完全相同,为什么不能使用完整的字母数组?

Why is it not working with the full alphabet array if they are both exactly the same size?

推荐答案

str_replacewith 数组只是按顺序执行所有替换.使用 strtr 来一次性完成所有操作:

str_replace with arrays just performs all the replacements sequentially. Use strtr instead to do them all at once:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');

这篇关于str_replace 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆