且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在php中将某些字符转换为数字?

更新时间:2023-02-19 12:23:20

使用 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).如果$destNULL0之外的其他内容,则为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值.