John
John

Reputation: 291

Avoid space from generated password code

If we run below code continuously, sometimes we found it generates some SPACE in the password which should not get.

Could anyone please tell how to avoid SPACE character from below generated password code:

Here is the code:

   function generateRandomPassword($length) {
      srand((double)microtime()*1000000);
      $password = "";
      $vowels = array("a", "e", "i", "o", "u");
      $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r",
"s", "t", "u", "v", "w", "tr", "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "
st", "sp", "sw", "pr", "sl", "cl");
      $num_vowels = count($vowels);
      $num_cons = count($cons);
      for($i = 0; $i < $length; $i++) {
         $c = $cons[rand(0, $num_cons - 1)];
         if (rand(0,1)) $c = strtoupper($c);
         $v = $vowels[rand(0, $num_vowels - 1)];
         if (rand(0,1)) $v = strtoupper($v);
         $password .= $c . $v;
         if (rand(0,4) == 0) $password .= rand(0,9);
      }
      return substr($password, 0, $length);
   }

$pwd = generateRandomPassword(12);

echo $pwd;

Upvotes: 1

Views: 67

Answers (1)

mega6382
mega6382

Reputation: 9396

Replace the return statement with the following:

  return trim(substr($password, 0, $length));

for all whitespace use:

return preg_replace('/\s+/', '', substr($password, 0, $length));

trim() Strip whitespace from the string. But the problem with your code is that there is a whitespace in the st of your $cons variable.

PhP trim Function

Upvotes: 2

Related Questions