可以说我有一些代码:

$text = $_POST['secret'];

$replaces = array(
        'a' => 's',
        'b' => 'n',
        'c' => 'v',
        'd' => 'f',
        'e' => 'r',
        'f' => 'g',
        'g' => 'h',
        'h' => 'j',
        'i' => 'o',
        'j' => 'k',
        'k' => 'l',
        'l' => 'a',
        'm' => 'z',
        'n' => 'm',
        'o' => 'p',
        'p' => 'q',
        'q' => 'w',
        'r' => 't',
        's' => 'd',
        't' => 'y',
        'u' => 'i',
        'v' => 'b',
        'w' => 'e',
        'x' => 'c',
        'y' => 'u',
        'z' => 'x',

                    );
    $text = str_replace(array_keys($replaces),array_values($replaces),$text);

echo "You're deciphered message is: ".$text;
}

?>

<form action="" method="post">
<p>Enter the secret message: <input name="secret" type="text"/></p>
<input class="button" type="submit" name="submit" value="Submit"/>

</form


在此,用户输入一个秘密消息,然后用新字符替换字符。对于键盘上的每个字母,它会替换为右侧的字母。

例如。如果用户输入“ gwkki”,则输出将为“ hello”。
但是上面的代码输出aaeae而不是hello。它输出“ aeaae”。这是因为字母h更改为j,然后j更改为k,然后k更改为l,然后l更改为a。以此类推。有什么办法可以对文本进行一次扫描和更改?

最佳答案

在PHP手册中,它清楚地说明了您的问题,在页面结尾,他们建议您使用strtr()来实现您想要的功能。

更换

  $text = str_replace(array_keys($replaces),array_values($replaces),$text);




  $text = strtr($text,$replaces);


完全满足您的要求,它将一个字符替换为另一个字符。

strtr()的文档在这里:http://www.php.net/manual/en/function.strtr.php

关于php - 如何用不会更新的新字母替换字符串中的字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8604550/

10-16 13:17
查看更多