我有以下代码,其中我将数字转换为字符串并输出一个句子。单词以“ +”号分隔。
例如,对于字符串 '16 8 16 + 20 5 19 20',输出应为 PHP TEST 。但是我得到的输出为 PHP T EST 。有人可以告诉我该怎么做吗?谢谢。
<?php
class NumbersToText
{
public static function numbersToLetters($string)
{
$arr = [
'A' => 1,
'B' => 2,
'C' => 3,
'D' => 4,
'E' => 5,
'F' => 6,
'G' => 7,
'H' => 8,
'I' => 9,
'J' => 10,
'K' => 11,
'L' => 12,
'M' => 13,
'N' => 14,
'O' => 15,
'P' => 16,
'Q' => 17,
'R' => 18,
'S' => 19,
'T' => 20,
'U' => 21,
'V' => 22,
'W' => 23,
'X' => 24,
'Y' => 25,
'Z' => 26,
];
$input = explode(' ', $string);
foreach ($input as $numval)
{
if (preg_match('/^[\d]+$/i', $numval))
{
echo array_search($numval, $arr);
}
if (strpos($numval, '+') !== FALSE)
{
$word = str_replace('+', ' ', $numval);
$wordbreak = explode(' ', $word);
foreach ($wordbreak as $split)
{
echo array_search($split, $arr);
echo " ";
}
}
}
}
}
echo NumbersToText::numbersToLetters('16 8 16+20 5 19 20');
答案 0 :(得分:1)
您可以改为在“ +”上爆炸,并且如果翻转阵列,将更容易输出字符。
$arr = array_flip($arr);
$str = '16 8 16+20 5 19 20';
$words = explode("+", $str);
foreach($words as $word){
$chrs = explode(" ", $word);
foreach($chrs as $chr){
echo $arr[$chr]; // echo the character
}
// Word ends, add space
echo " ";
}
//PHP TEST
答案 1 :(得分:0)
关联数组是不必要的。使用chr
将整数加64转换为正确的ASCII位置:
$str = "16 8 16+20 5 19 20";
foreach (explode("+", $str) as $digits) {
echo preg_replace_callback("~\d+ ?~", function ($e) {
return chr((int)$e[0] + 64);
}, $digits) . " ";
}
输出:
PHP TEST