Alexander
Alexander

Reputation: 153

PHP Replace each letter from words

I need a function to replace each letter from a word with other letters. For example:

a = tu
b = mo
c = jo

If I write "abc", I want to get "tumoji", if I write "bca" I want to get "mojotu", etc.

Upvotes: 2

Views: 865

Answers (2)

Mark Baker
Mark Baker

Reputation: 212412

$from = array('a',
              'b', 
              'c'
             );
$to = array('tu',
            'mo', 
            'jo'
           );
$original = 'cab';
$new = strtr($original,$from,$to);

or

$replacements = array('a' => 'tu',
                      'b' => 'mo', 
                      'c' => 'jo'
                     );
$original = 'cab';
$new = strtr($original,$replacements);

or

$replacements = array('a' => 'tu',
                      'b' => 'mo', 
                      'c' => 'jo'
                     );
$original = 'cab';
$new = '';
foreach(str_split($original) as $letter) {
    $new .= $replacements[$letter];
}

Upvotes: 4

alex
alex

Reputation: 490233

Use strtr().

$str = strtr($str, array('a' => 'tu' /*, ... */));

Upvotes: 3

Related Questions