duandui2803 2014-05-19 18:09
浏览 55

尝试str_replace连接字符串+整数,获得不稳定的行为

if (isset($values) && count($params) == count($values))
    {
        $counter = 0;
        $html = str_replace('mxyzptlk', 'value', $html);

        foreach ($values as $value)
        {
            $string = 'klf' . strval($counter);
            $html = str_replace($string, $value, $html);
            $counter++;
        }
    }

This is a fairly simple piece of code. Earlier in the program, I generate a list of values using a loop that results in the following:

klf0 klf1 klf2 klf3 ... klf19 klf20

The loop above is supposed to go through this list of "klf" values and replace them with something else.

The weird thing that is happening is that the entire page works fine, until the loop gets to "klf10" and above. What happens then is that the strings are being truncated, changing "klf10" to "0" and "klf11" to "1" and so on. Something about double digits is screwing this up.

Like I said, the code works fine up to the str_replace function-- outputting $string right before it results in proper values ("klf10") and outputting $value right before the str_replace shows the right value to replace "klf(n)" with.

Any ideas as to why it's doing this? I tried converting the integer parts to strings but it obviously didn't help.

Edit: I have confirmed that the strings aren't actually being truncated, but "klf10" is in fact being partially replaced by the value of "klf1." I'm going to keep playing around with it but thought it might help in diagnosis.

  • 写回答

1条回答 默认 最新

  • duanhan9334 2014-05-19 18:46
    关注

    Didn't realize str_replace replaces all occurrences in a string. At the beginning of the loop "klf1" is being replaced in every instance; "klf1," "klf10" and "klf12" are all being mangled as a result.

    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计