Home > front end >  Add a random character to a string every second character
Add a random character to a string every second character

Time:10-29

How can I add random character from [A-Za-z0-9] / or - to a string every second character? e.g.

Hello_world!

becomes

H3e7l2l-o2_aWmocr9l/db!s

Edit: Here is what I tried:

$char = substr(str_shuffle(str_repeat($charset, 11)), 0, 11);
$d = "Hello_World!";
$r = str_split($d, 2);
$added = implode($char, $r);

CodePudding user response:

$str = 'Hello_world!';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-';
$result = array_reduce(str_split($str),
  fn($carry, $item)=>$carry.=$item.$chars[rand(0,strlen($chars)-1)], '');
print_r($result);

str_split splits your input string into characters, then array_reduce recombines them with the random chars added.

CodePudding user response:

<?PHP
  $str =  "Hello World!";
  
  $new_string = '';
  for($i =0; $i < strlen($str); $i  ){ // loop through the string
     $new_string .= $str[$i]; // add character to new string
     $new_string .= getRandomCharacter(); // add the random character to new string
  }
  echo $new_string;
  
  function getRandomCharacter(){
     $random_characters = 'abcdefghijklmnopqrstuvwxyz'
                 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 .'0123456789!@#$%^&*()';
    $index= rand(0, (strlen($random_characters)- 1) ); // generates random character index from the given set.
    return $random_characters[$index];
  }
  
?>
  •  Tags:  
  • php
  • Related