使用 PHP 八进制和字符串转换
我正在使用一个数据库,该数据库包含一堆以前导 0 为前缀的序列号。
因此,序列号可能看起来像 00032432 或 56332432。
PHP 的问题是我不明白八进制转换系统是如何工作的。
一个具体的例子是,我试图将所有这些基于整数的数字与字符串进行转换和比较。
是否可以将八进制(例如 00234)转换为“00234”这样的字符串,以便我可以比较它?
编辑 - 添加一个具体示例。我希望能够在串行上运行 str 函数,如下所示。
$serial = 00032432; // coming from DB
if(substr($serial, 0, 1) == '0') {
// do something
}
I'm working with a database that has a bunch of serial numbers that are prefixed with leading 0's.
So a serial number can look like 00032432 or 56332432.
Problem is with PHP I don't understand how the conversion system with octals works.
A specific example is that I'm trying to convert and compare all of these integer based numbers with strings.
Is it possible to convert an octal, such as 00234 to a string like "00234" so that I can compare it?
edit - adding a specific example. I would like to be able to run str functions on the serial like below.
$serial = 00032432; // coming from DB
if(substr($serial, 0, 1) == '0') {
// do something
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当你用
(string) $number
转换时,你总是得到一个十进制的字符串,无论你以八进制模式还是十进制模式写数字都没关系,int就是int,它本身没有基础。这是他的字符串表示形式,必须用基数来解释。您可以通过以下方式获取数字的八进制字符串表示形式:
或以十进制表示形式给出数字:
或者,更简洁但不太清楚:
最后,隐式进行字符串转换。这些示例给出了所有结果 $str = "32432"。
base_convert 将数字的字符串表示形式从基数转换为另一个基数
如果您还想要字符串中的零,则可以通过简单的数学将它们相加。
希望这可以帮助你。
When you convert with
(string) $number
, you always get a string in decimal base, it doesn't matter if you write the number in octal mode or in decimal mode, an int is an int and it has not itself a base. It's his string representation that have to be interpreted with a base.You can get the octal string representation of a number in this way:
or giving the number in decimal rep:
or, more concisely but less clearly:
In the last the string conversion is made implicitly. The examples give all as result $str = "32432".
base_convert converts a string representation of a number from a base to another
If you want also the zeros in your string, you can add them with simple math.
Hope this can help you.
要将八进制转换为字符串,请对其进行强制转换:
您可以使用函数 octdec 和 decoct 在八进制和十进制之间进行转换
http://uk.php.net/manual/en/function.octdec.php
To convert an octal to a string, cast it:
You can convert between octal and decimal with the functions octdec and decoct
http://uk.php.net/manual/en/function.octdec.php
数据库中的所有内容都会自动成为字符串。整数是字符串,日期是字符串,狗是字符串。
如果您正在做一些奇怪的事情,请通过以下方式将任何内容转换为字符串:
$a = (string) 12;
Everything from the database is automatically a string. Integers are strings, dates are strings, dogs are strings.
If you are doing something weird, convert anything to a string by:
$a = (string) 12;