duanmao1872 2012-07-12 22:19
浏览 33
已采纳

为什么从字符串到整数的类型转换总是返回“0”?

I'm writing an AJAX chat script and I'm integrating a system to parse the time (basically like BBCode). The problem is, when I try casting the time (UNIX timestamp) to an integer for use with date(), it always returns "0". The code I am using to find and replace is below. I've also added a sample of what I'm trying to parse

$out = preg_replace("/\[time\](.*)\[\/time\]/i",date("c",(int)"$1",$out);

Sample:

<b>GtoXic</b>: [time]1342129366[/time]
  • 写回答

3条回答 默认 最新

  • dqybjj3497 2012-07-12 22:24
    关注

    Because what you are actually casting to an integer is the literal string $1, and converting a string to an integer works in the following way:

    • If the start of the string is a valid numeric representation, use that until we come across a character incompatible with that format
    • Otherwise return zero

    In order to get this to work, you would use preg_replace_callback():

    $output = preg_replace_callback("/#\[time\](.*)\[/time\]#i", function ($matches) {
      return date("c", $matches[1]);
    }, $input);
    

    The (int) cast is actually unnecessary, PHP will automatically handle this when you pass the value to a function that expects an integer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备