str_replace 与数组的意外行为 [英] unexpected behaviour of str_replace with array

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

问题描述

我有以下函数,使用 str_replace 会产生意想不到的结果

I've the following function and using str_replace gives an unexpected result

function repo($text) {
    $search = array("0","1","2","3","4","5","6","7","8","9");
    $replace = array("z30","z31","z32","z33","z34","z35","z36","z37","z38","z99");
    $text = str_replace($search,$replace,$text);
    return $text;
}

echo repo('0');

预期的答案是

z30

相反,我得到

zz330

我做错了什么?

推荐答案

你的函数就是这样工作的.

Your function works this way.

0 更改为 z30,php 继续循环数组,然后 z30 包含 '3',3 更改为 z33.因此返回 'z' + 'z33' + '0' = zz330.

0 changes to z30, php continues loop the arrays, then z30 contains '3', and 3 changes to z33. Because of that returns 'z' + 'z33' + '0' = zz330.

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

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