skip to Main Content

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

Hello_world!

output:

H3e7l2l-o2_aWmocr9l/db!s

Edit:
Here is what I’ve tried, however without the line below the one marked Here that throws an error

Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in....

I guess it’s because a fragment of $char is not an array.
After I’d added the line below Here to "convert" the string to array another error appeared:

Uncaught TypeError: str_repeat(): Argument #1 ($string) must be of type string, array given in...

<?php
$string = "Hello_World!";
$length = strlen($string);
$string = str_split($string, 2);
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-";

//Here 
$chars = (is_array($chars)) ? $chars : [$chars];

for($i = 0; $i < ($length / 2); $i++){
  $char = substr(str_shuffle(str_repeat($chars, 1)), 0, 1);
  $added = implode($string[$i], $char);
}

echo $string;

?>

3

Answers


  1. <?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];
      }
      
    ?>
    
    Login or Signup to reply.
  2. $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.

    Login or Signup to reply.
  3. Since your inputs are both strings AND the pool of random characters contains only single-byte characters, this task can be directly achieved with no array functions and no concatenation.

    Call for a random letter to be inserted in the original string after each letter via preg_replace_callback().

    Code: (Demo)

    $str = 'Hello_world!';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-';
    $max = strlen($chars) - 1;
    
    echo preg_replace_callback(
        '/.K/',
        fn() => $chars[rand(0, $max)],
        $str
    );
    

    K tells the regex engine to forget the previously matched character. This results in no characters being lost — the random letter is added at the zero-width position after each character.


    If you were dealing with input arrays, then it might be worth reading Implode array with array of glue strings for a clever vprintf() trick.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search