PHP 将数字更改为 str_replace 的字符串而不混淆

PHP changing numbers to the strings with str_replace without mixed up

我正在将数字更改为字符串。像那样:

1=>A
2=>B
3=>C
4=>D
5=>E
6=>F
7=>G
8=>H
9=>I
10=>J
11=>K
12=>L

我将此功能替换为:

function name($string) {
    $find=array("1","2","3","4","5","6","7","8","9","10","11","12");
    $replace=array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L");
    $string=str_replace($find,$replace,$string);  
    return $string;
}

但是如果我使用这个:name("12"); 它不是 returning L 它 return AB.

其实是有道理的。返回每个字母。我如何在这个函数中 return L ?我应该怎么办?提前致谢。

问题是 str_replace() 只是按照您在 documentation...

中指定的顺序替换它们

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

如果您改为使用 strtr(),它将首先替换最长的...

$string=strtr($string, array_combine($find, $replace));

创建一个简单的映射:

$mapping = [
    '1' => 'A',
    '2' => 'B',
    '12' => 'L',
];
if (!array_key_exists($string, $mapping)) {
    throw new Exception('invalid input provided');
}
return $mapping[$string];

你确实有一个 PHP 函数来实现你想要实现的目标 - chr

<?php 

function name($string) {
   return chr(intval($string) + 64);
}

更新:

  • 感谢@Ulrich。您可以使用 ord('A') 更好地描述上述解决方案。所以,基本上,您将 A 的 ASCII 值添加到整数转换后的字符串参数中,然后从中减去 1,以获得我们要查找的字符的 ASCII 值。 chr() 终于给了我们那个角色。

function name($string) {
   return chr(intval($string) + ord('A') - 1);
}

如果我不明白你的问题,那么,请尝试使用 range() 而不是长 key=>value 数组.我认为对于您当前的要求 str_repalce() 不是一个好的选择,简单的 range() 就可以发挥作用 :)

<?php
  function name($num){
    $array = range('A','Z');
    $array = array_filter(array_merge(array(0), $array));
    return $array[$num];
  }

 echo name(12);

演示: https://3v4l.org/kl9jn

str_replace() 用数组替换提供的字符串与数组项中的任何匹配项。所以使用底部显示的 array_search() 代替

$result = $replace[array_search($string, $find)]; 

因此您的代码更改为

function name($string) {
    $find = array("1","2","3","4","5","6","7","8","9","10","11","12");
    $replace = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L");  
    return $replace[array_search($string, $find)]; 
}

检查结果 demo

而不是 str_replace 使用 chr

function name($string) {
    return chr( $string + 64 );
}

请注意,只要 $string 实际上包含 1 .. 26

范围内的数字,这就是单词

但是如果 - 由于某种原因 - 你想坚持使用 str_replace 方法,解决方案是用前导和后跟 space(或你选择的字符...... ), 这样:

function name($string) {
    $string = " " . $string . " ";
    $find=array(" 1 "," 2 "," 3 "," 4 "," 5 "," 6 "," 7 "," 8 "," 9 "," 10 "," 11 "," 12 ");
    $replace=array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L");
    $string=str_replace($find,$replace,$string);  
    return $string;
}