将单词中的所有字符转换为PHP中的整数

问题描述 投票:3回答:4

是否可以将单词中的所有字符转换为数字

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

看到一些相关的问题,但它没有直接回答我的问题,我不能完全理解并解决所有问题,所以我在这里问。

php string numbers converters
4个回答
1
投票

创建一个数组,并在第一个元素中插入一个空格。然后使用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);
}

1
投票

这是完整的代码:

$s = 'abcde';
$p = str_split($s);
foreach($p as $c) {
    echo ord($c) - ord('a') + 1;
}

1
投票

要使用你展示的数字a = 1等...然后只做一个不区分大小写的替换:

$result = str_ireplace(range('a', 'z'), range(1, 26), $string);

如果你想要ASCII值然后拆分成一个数组,映射到ord值并加入:

$result = implode(array_map(function($v) { return ord($v); }, str_split($string)));

0
投票

使用正则表达式应该是这样的:

$search  = array('/[A-a]/', '/[B-b]/', '/[C-c]/', '/[D-d]/', '/[" "]/');
$replace = array('1', '2', '3', '4', '5');

$final = preg_replace($search, $replace,"abcd ABCD a55");

echo $final;

Output: 1234512345155
© www.soinside.com 2019 - 2024. All rights reserved.