如何在php中将某些字符转换为数字? [英] How to convert some character into numeric in php?
问题描述
我需要帮助来更改php中的字符. 我从网上得到了一些代码:
I need help to change a character in php. I got some code from the web:
char dest='a';
int conv=(int)dest;
我可以使用此代码将字符转换为数字吗?还是您有什么想法? 我只想将结果显示为十进制数字:
Can I use this code to convert a character into numeric? Or do you have any ideas? I just want to show the result as a decimal number:
if null == 0
if A == 1
推荐答案
使用 ord() 以返回ascii值.减去96返回一个数字,其中a = 1,b = 2 ....
Use ord() to return the ascii value. Subtract 96 to return a number where a=1, b=2....
大写和小写字母具有不同的ASCII值,因此,如果要处理相同的ASCII值,则可以使用 strtolower() 将大写转换为小写.
Upper and lower case letters have different ASCII values, so if you want to handle them the same, you can use strtolower() to convert upper case to lower case.
要处理NULL
情况,只需使用if($dest)
.如果$dest
是NULL
或0
之外的其他内容,则为true.
To handle the NULL
case, simply use if($dest)
. This will be true if $dest
is something other than NULL
or 0
.
PHP是一种松散类型的语言,因此无需声明类型.因此char dest='a';
是不正确的.变量在PHP中具有$
前缀,并且没有类型声明,因此应为$dest = 'a';
.
PHP is a loosely typed language, so there is no need to declare the types. So char dest='a';
is incorrect. Variables have $
prefix in PHP and no type declaration, so it should be $dest = 'a';
.
<?php
function toNumber($dest)
{
if ($dest)
return ord(strtolower($dest)) - 96;
else
return 0;
}
// Let's test the function...
echo toNumber(NULL) . " ";
echo toNumber('a') . " ";
echo toNumber('B') . " ";
echo toNumber('c');
// Output is:
// 0 1 2 3
?>
PS: 您可以在此处查看ASCII值.
这篇关于如何在php中将某些字符转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!