在PHP中将单词中的所有字符转换为整数
是否可以将一个单词中的所有字符转换为数字在PHP中将单词中的所有字符转换为整数,php,string,numbers,converters,Php,String,Numbers,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 in
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
看到一些相关的问题,但它没有直接回答我的问题,我不能完全理解和解决它,所以我在这里问 以下是完整的代码:
$s = 'abcde';
$p = str_split($s);
foreach($p as $c) {
echo ord($c) - ord('a') + 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)));
创建一个数组,并在第一个元素中插入一个空格。然后使用
range()
生成一个数组,其中a
到z
。使用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);
}
- 现场演示
$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
大写字母呢?
A
1也是吗?是的,mybad没有想到。我编辑了它,这样其他人就不会对大小写敏感度感到困惑。它也适用于A-z吗?