Replacing text

I want to create a text box where people can enter words in… such as “Hello Sitepoint”

After submitting, it would then select each letter entered and replace with a different letter, for example:

a b c d e f g h i j k l m n o p q r s t u v w x y z

i h k j m l o n q p s r u t w v y x a z c b e d g f

hello would then convert to:

nmrrw

How would I go about doing a big replace like this?

Thanks.

The following should be pretty self explanatory. :slight_smile:


<?php
echo strtr(
    'Hello World',
    #your mapping
    array(
        'o' => 'x',
        'l' => 'g'
    )
); #Heggx Wxrgd
?>

Interesting cases:

<?php
$string  = "Hello Sitepoint";

#Case1
$search_array = explode(" ", "a b c d e f g h i j k l m n o p q r s t u v w x y z");
$replace_array = explode(" ", "i h k j m l o n q p s r u t w v y x a z c b e d g f");
echo str_replace($search_array, $replace_array, strtolower($string));//prints: fcdde agfcbegff <--< wrong

#Case2
echo strtr(strtolower($string), array_combine($search_array, $replace_array)); //prints: nmrrw aqzmvwqtz <--< Right
?>

So care should be taken in using str_replace in case of re-occurring letters
as str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. Example is obvious from the first case.

hope this gave some idea.
Thanks