通过基于关联数组替换用户输入来生成代码

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

我有一个由十六进制字符组成的 16 个字符的输入字符串。我需要隔离最后两个字符,通过重复这两个隔离字符将该字符串扩展到四个字符,然后使用关联查找/映射替换它们。

我的示例输入是:

$atcode = '11F5796B61690196';

我的关联数组是:

$sub1 = [
    '0' => '2',
    '1' => '3',
    '2' => '0',
    '3' => '1',
    '4' => '6',
    '5' => '7',
    '7' => '5',
    '8' => 'A',
    '9' => 'B',
    'A' => '8',
    'B' => '9',
    'C' => 'E',
    'D' => 'F',
    'E' => 'C',
    'F' => 'D'
];

孤立的字符应该是

9
6

想要的结果是:

B6B6

这是到目前为止的代码:

$codearray = str_split($atcode);
    
//select the 15th digit from $codearray and name it $one
$one = $codearray[14];
    
//create an associative array and name it $sub1
$sub1 = array('0' => '2', '1' => '3', '3' => '1', 'D' => 'F', '4' => '6', '5' => '7', '7' => '5', '8' => 'A', '9' => 'B', 'A' => '8', 'B' => '9', 'C' => 'E', '2' => '0', 'E' => 'C', 'F' => 'D');
    
//search through $sub1, determine which value is equivalent to $one, and select its equivalency from the key to value pairs
$codeone = array_replace($one, $sub1);
    
//select the 16th digit from $codearray and name it $two
$two = $codearray[15];
    
echo "$codeone", "$two"; 

但是,我只是得到一个空白页。

php replace substring translation
3个回答
1
投票

放弃大部分代码。

提取最后两个字符,重复它们,然后用

strtr()
翻译它们。

代码:(演示

$atcode = '11F5796B61690196';

var_export(
    strtr(
        str_repeat(substr($atcode, -2), 2),
        '012345789ABCDEF',
        '2301675AB89EFCD'
    )
);

0
投票

初始化后

$atcode
,我建议您可以将代码简化为:

$sub1 = array('0' => '2', '1' => '3', '3' => '1', 'D' => 'F', '4' => '6', '5' => '7', '7' => '5', '8' => 'A', '9' => 'B', 'A' => '8', 'B' => '9', 'C' => 'E', '2' => '0', 'E' => 'C', 'F' => 'D');
echo str_repeat($sub1[$atcode[14]] . $atcode[15], 2);

0
投票

更改 $codeone = array_replace($one, $sub1);到 $codeone = $sub1[$one];

$codearray = str_split("11F5796B61690196");
    
    
    $one = $codearray[14];

// Create an associative array and name it $sub1
$sub1 = array('0' => '2', '1' => '3', '3' => '1', 'D' => 'F', '4' => '6', '5' => '7', '7' => '5', '8' => 'A', '9' => 'B', 'A' => '8', 'B' => '9', 'C' => 'E', '2' => '0', 'E' => 'C', 'F' => 'D');

// Search through $sub1, determine which value is equivalent to $one, and select its equivalency from the key to value pairs
$codeone = $sub1[$one];

// Select the 16th digit from $codearray and name it $two
$two = $codearray[15];

// Output the 4-digit code
echo $codeone . $two.$codeone . $two;

这应该给B6B6

© www.soinside.com 2019 - 2024. All rights reserved.