如何防止PHP在条件条件下进行八进制数学运算? (为什么08 === 0) [英] How to prevent PHP from doing octal math in conditionals? (why does 08 === 0)

查看:82
本文介绍了如何防止PHP在条件条件下进行八进制数学运算? (为什么08 === 0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用解析crontab的代码。

I was working with code that parses crontab.

https:/ /stackoverflow.com/a/5727346/3774582

我发现它很好用,但是我发现如果我做成了cron这样的

I found it works great, however I found that if I made a cron like

0 * * * *

它将在0分钟,8分钟和9分钟运行。我破坏了代码的每一行。

It would run at the 0 minute, the 8th minute, and the 9th minute. I broke down every line of the code.

https://gist.github.com/goosehub/7deff7928be04ec99b4292be10b4b7b0

我发现如果当前分钟为0,则该条件为0 8。

I found that I was getting this conditional for the value of 0 if the current minute was 8.

08 === 0

我用PHP

if (08 === 0) {
    echo 'marco';
}

运行之后,我看到了 marco 在输出上。看来PHP将 08 视为八进制。因为在 07 之后的八进制是 010 08 09 被评估为 00

After running that, I saw marco on the output. It appears PHP is treating 08 as an octal. Because in octal after 07 is 010, 08 and 09 is evaluated as 00.

如何强制

推荐答案

来自Integer的PHP文档

From the PHP docs in Integer

http://php.net/manual/en/language.types .integer.php


要使用八进制表示法,请在数字前加上0(零)。

To use octal notation, precede the number with a 0 (zero).

但是,不要只使用 ltrim($ time [$ k],'0'),因为这会将 0 转换为 。而是使用正则表达式。在这种情况下, / ^ 0 +(?= \d)/

However, don't just use ltrim($time[$k], '0') because this will turn 0 into . Instead, use a regular expression. In this case, /^0+(?=\d)/.

在这种情况下,请套用像这样输入到 $ time [$ k] 输入。

In this case, apply it to the $time[$k] input like so.

$time[$k] = preg_replace('/^0+(?=\d)/', '', $time[$k]);

这篇关于如何防止PHP在条件条件下进行八进制数学运算? (为什么08 === 0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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