我在使用数组时遇到了 PHP 函数 str_replace
的一些问题。
我有这条消息:
$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");
我正在尝试像这样使用 str_replace
:
$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
。
但是,当我只尝试替换 2 个字母时,它会很好地替换它们:
$new_message = str_replace(array('l','p'), array('a','e'), $message);
字母 l
和 p
将被替换为 a
和 e
。
如果它们的大小完全相同,为什么它不能使用完整的字母数组?
最佳答案
因为 str_replace() 从左到右替换,所以在进行多次替换时,它可能会替换先前插入的值。
// Outputs F because A is replaced with B, then B is replaced with C, and so on... // Finally E is replaced with F, because of left to right replacements. $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject);
关于php - str_replace 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13715826/