如何用不会更新的新字母替换字符串中的字母 [英] How to replace a letter in a string with a new letter that will not be updated

查看:118
本文介绍了如何用不会更新的新字母替换字符串中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说一些代码:

$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

在此,用户输入一个秘密消息,然后用新字符替换字符.键盘上的每个字母都会被右侧的字母替换.

Here, a user inputs a secret message, and then the characters are replaced by new characters. For every letter on a keyboard it is replaced with the letter to the right.

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

eg. if a user enters "gwkki" the output will be "hello". However the above code outputs aeaae and NOT hello. It outputs "aeaae". This is because the letter h changes to j, then j changes to k, then k changes l, then l changes to a. and so on with the other letters. Is there any way for the text to be scanned and changed once??

推荐答案

在PHP手册中清楚地说明了您的问题,在页面结尾,他们建议您使用完全符合您要求的strtr().

In the PHP Manual it's clearly explained your problem, at the end of the page they advice to use strtr() which does exactly what you want.

替换

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

使用

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

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

which does exactly what you want, it replaces one character with another character.

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

The documentation of strtr() is here: http://www.php.net/manual/en/function.strtr.php

这篇关于如何用不会更新的新字母替换字符串中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆