chillers
chillers

Reputation: 1457

Replace a random letters in a string with a matching one

I'm trying to replace letter or letters in a string with a matching letter but I want it to be random.

$string = "This is random text in this string.";

Here are a few examples of letter I would change below s = $,o = 0,i = l

I'm trying to randomly replace letters in that string above and the output would look like this below. It would be all random and wouldn't need to change all the letters just a few at random that match the letters above.

Output Examples

This is rand0m text in this $tring.

Thi$ is random text in this string.

How would I go about doing this in PHP?

Upvotes: 3

Views: 969

Answers (2)

mk_89
mk_89

Reputation: 2742

Can't get any more random than this. add to the array $a for more replacement characters

$str = 'This is random text in this string.';
$str2 = '';

function repl($char){
    $arr = array(
        's' => '$',
        't' => 'T'
    );

    foreach($arr as $key=>$a){
        if($char == $key) return $a;
    }
    return $char;
}


foreach(str_split($str) as $char){
    if(!rand(0, 9))     $str2 .= repl($char);
    else                $str2 .= $char;

}

echo $str."\n";
echo $str2;

Upvotes: 1

Federkun
Federkun

Reputation: 36934

What about something like

$string = "This is random text in this string.";

$replace = array('s' => '$', 'o' => '0', 'i' => '1');
foreach(array_rand($replace, (count($replace)/2)+1) as $key) {
    $string = str_replace($key, $replace[$key], $string);
}

Demo.

Upvotes: 1

Related Questions