tags:

views:

375

answers:

4

i would like to scramble all a-zA-Z so a world like

hello becomes shrxs or bhidf

the rest should stay the same. eg. "hello world!"="ksgii fishl!"

etc.

+8  A: 

It's not clear whether this is intended to be reversible, so here are two alternative answers.

"hello" becoming "shrxs" implies a scheme that goes beyond simple subsitution (a caesar cipher) and perhaps something like a polyalphabetic cipher.

But for a simple caesar cipher you can use strtr

$plain="hello";
$cipher = strtr($plain, 
    "abcdefghijklmnopqrstuvwxyz", 
    "tuvhijkcwxyzldefgsmnopqrab");
echo $cipher;

Would display "cizze";

If you don't need to reverse the scrambling, and want something truly random, try this

function random_char($matches)
{
   return chr(rand(ord('a'),ord('z')));
}

$plain="hello";

$random=preg_replace_callback(
           "{[a-z]}i",
           "random_char",
           $plain);

echo $random;

Here we use preg_replace_callback to have each char replaced with a random alternative by the random_char callback.

Paul Dixon
+1 strstr can do any simple substitution cipher (for what it's worth which isn't a lot)
cletus
+1  A: 

What exactly do you mean by scramble? I can see you're not rearranging or counting letters through the alphabet.

It sounds like you just wanted to know how to replace only a-zA-Z characters. So whatever your transformation function might be, this is one way you could do it:

$result = preg_replace_callback('/[a-zA-Z]/', 'charTransform', $oldstring);

Then define the transform as a callback:

function charTransform($matches) {
   $oldchar = $matches[0];
   return strtolower($oldchar); // replace with whatever you want
}
Ray Hidayat
Beaten to it again!
Ray Hidayat
+1  A: 

The question is, would you like the text scrambled or encrypted, i.e. should the text be decryptable or not? If you just want all letters replaced by some other random letter you might try something like this:

$text = "Hello world!\n";
$text = preg_replace_callback(
        '/[a-zA-Z]/',
        create_function('$matches', 'return chr(rand(97,122));'),
        $text
    );
cg
+3  A: 

You might also like to look at the str_rot13 function, which has the advantage of being reversible too.

<?php
  var $foo = "hello world!";
  var $bar = str_rot13($foo); // $bar equals "uryyb jbeyq!"
  var $baz = str_rot13($bar); // $baz equals "hello world!"
?>
David Grant