Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

php - How to replace a letter in a string with a new letter that will not be updated

Lets say I have some code:

$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.

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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Replace

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

with

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...