我想以这种方式将字母转换为数字:A=0, B=1, C=2... Z=25 使用 php
I want to convert alphabets to numbers, in this way: A=0, B=1, C=2... Z=25 using php
我想编写一个函数,将输入作为字符串并将字母转换为数字,然后 returns 转换后的数字,这样:A(a)=1, B(b)=2, C(c)=3... Z(z)=25 使用 php
提前致谢
请试试这个:
function conv($alph=null){
return (!is_null($alph)?strpos("abcdefghijklmnopqrstuvwxyz", $alph):"Need String");
}
echo "<br /><br />";
echo conv("a");
编辑:
$str = "abcDefghZ";
$out = "";
for($i=0;$i<strlen($str);$i++){
$out .= conv(strtolower($str[$i]));
}
echo $str."<br />".$out;
如果您尝试使用自己的哈希函数:不要。
如果您需要接受来自 ASCII 的其他字符,请使用 PHP 的 ord() 函数。
试试这个:
此函数 returns 位置,并且可以根据需要接受一个基本整数来移动数字。
function alpha_ord($str, $base = 0) {
$pos = stripos(
'abcdefghijklmnopqrstuvwxyz',
$str{0}
);
if ($pos !== FALSE) {
$pos += $base;
}
return $pos;
}
print alpha_ord('A'); // 0
print alpha_ord('Z', 1); // 26
print alpha_ord('Z'); // 25
print alpha_ord('A', 65); // 65
首先,我们将所有内容设为小写。
然后,使用ord
函数,我们得到ascii码,然后从中减去'a'。
function one_char_map($chr)
{
$chr=strtolower($chr);
return ord($chr)-ord('a');
}
function string_map($str)
{
return implode(array_map('one_char_map',str_split($str)));
}
echo string_map('abcD');//0123
我想编写一个函数,将输入作为字符串并将字母转换为数字,然后 returns 转换后的数字,这样:A(a)=1, B(b)=2, C(c)=3... Z(z)=25 使用 php 提前致谢
请试试这个:
function conv($alph=null){
return (!is_null($alph)?strpos("abcdefghijklmnopqrstuvwxyz", $alph):"Need String");
}
echo "<br /><br />";
echo conv("a");
编辑:
$str = "abcDefghZ";
$out = "";
for($i=0;$i<strlen($str);$i++){
$out .= conv(strtolower($str[$i]));
}
echo $str."<br />".$out;
如果您尝试使用自己的哈希函数:不要。
如果您需要接受来自 ASCII 的其他字符,请使用 PHP 的 ord() 函数。
试试这个:
此函数 returns 位置,并且可以根据需要接受一个基本整数来移动数字。
function alpha_ord($str, $base = 0) {
$pos = stripos(
'abcdefghijklmnopqrstuvwxyz',
$str{0}
);
if ($pos !== FALSE) {
$pos += $base;
}
return $pos;
}
print alpha_ord('A'); // 0
print alpha_ord('Z', 1); // 26
print alpha_ord('Z'); // 25
print alpha_ord('A', 65); // 65
首先,我们将所有内容设为小写。
然后,使用ord
函数,我们得到ascii码,然后从中减去'a'。
function one_char_map($chr)
{
$chr=strtolower($chr);
return ord($chr)-ord('a');
}
function string_map($str)
{
return implode(array_map('one_char_map',str_split($str)));
}
echo string_map('abcD');//0123