Generate a Random String of Same Pattern as Given String

Here is a PHP snippet showing how to generate a random string of same pattern as input string.

<?php

/**
 * Generates a random string of same patter as input string.
 */
function generate_random_string($input) {
  $length = strlen($input);
  $output = '';
  for ($i = 0; $i < $length; $i++) {
      $character = $input[$i];
      if (preg_match('/[a-z]/', $character)) {
        $output .= chr(random_int(97, 122));
      }
      else if (preg_match('/[A-Z]/', $character)) {
        $output .= chr(random_int(65, 90));
      }
      else if (preg_match('/\d/', $character)) {
        $output .= chr(random_int(48, 57));
      }
      else {
        $output .= $character;
      }
  }
  return $output;
}

$examples = [
  'asb-sds-134-asa',
  '1234',
  'a12bc',
  '342 2323223232-9',
];

foreach ($examples as $example) {
  $random_string = generate_random_string($example);
  echo "$example => $random_string" . PHP_EOL;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *