Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a random letters in a string with a matching one

Tags:

php

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?

like image 445
chillers Avatar asked Dec 06 '25 02:12

chillers


1 Answers

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;
like image 103
mk_89 Avatar answered Dec 08 '25 14:12

mk_89