php - 将非数字字符转换为特定数字

标签 php string numbers translation converters

是否可以将字符串中的字符转换为特定的数字,如

a = 1,  // uppercase too
b = 2,  
c = 3,  
d = 4,  
e = 5,  // and so on til letter 'z'

space = 0 // I'm not sure about if space really is equals to 0

这是我的想法。

$string_1 = "abed";   // only string
$string_2 = "abed 5"; // with int

$result_1 = convert_to_int($string_1); // output is 1254
$result_2 = convert_to_int($string_2); // output is 125405

最佳答案

创建一个数组,并在第一个元素中插入一个空格。然后使用range()生成一个az的数组。使用 strtolower() 强制输入小写(因为我们生成的 range() 中的字符也是小写的。

然后使用接受数组作为值的 str_replace() 进行替换。键是值将被替换的值。

function convert_to_int($string) {;
    $characters = array_merge([' '], range('a', 'z'));
    return str_replace(array_values($characters), array_keys($characters), $string);
}

关于php - 将非数字字符转换为特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55406430/

相关文章:

php - MySQL 5.0.12 - 列表不在 GROUP BY 子句中并且包含非聚合列?

c - c : (negative)0 is not equal to 0 中的双变量类型

java - 从另一个类调用方法的不同方式

java - 如何从控制台的一个输入读取字符串和整数?

java - 将包含十六进制 0x00 的字符串复制到剪贴板

Python:一个月中的周数

java - 我想检查负数和非数

php - 通过 PHP 建立隧道代理

php - Laravel 返回 Patchwork\\utf8\\Bootup 错误

php - 表单验证 - jQuery 验证是否足够以及如何巧妙地验证 PHP 中的数据?