Advertisement
gitlez

Untitled

Nov 26th, 2011
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /*
  3.   Cleaned up and sped up.
  4.   1000 interations of producing 2000 char string:
  5.     Original - 4.1486458778381 seconds
  6.     This rewrite - 2.3620591163635
  7.     %43 percent improvement
  8. */
  9.  
  10. function cw_randchar( $length=NULL, $case=NULL, $spaces=false){
  11.   // setting $spaces to null, then checking if null, is a waste of resources and effort. Just set it to false. Then the user can switch it on if they desire.
  12.   if(!is_numeric($length)){
  13.     $temp_length = $length;
  14.     if(strpos($temp_length,',') !== false){ // strpos is faster/less resource intensive as strstr
  15.       $temp_length = str_replace(',','',$temp_length); //str_replace is faster than preg_replace(). RegEx have there place, but are huge wastes of resources. Know when to use them and when not to. This is not a case where RegEx are needed.
  16.     }
  17.     $length = (is_numeric($temp_length))? $temp_length : strlen($length);
  18.   }
  19.   $length = (int)$length;
  20.   if($length === 0){
  21.     $length = 8;
  22.   }else if($length > 2000){
  23.     $length = 2000;
  24.   }
  25.   // Note with strpos() - it can return a position of 0 (beginning of the string), so you need to check against the boolean false, to ensure PHP doesn't interprut the 0 as false;
  26.   if(stripos($case,'lower') !== false){
  27.     $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
  28.   }else if(stripos($case, 'upper') !== false){
  29.     $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  30.   }else{
  31.     $characters = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  32.   }
  33.   if($spaces){
  34.     $characters .= ($case)? str_pad('',16,' ') : str_pad('',8,' ');
  35.   }
  36.   // No need for the is_bool() check as default is false
  37.   $chrLen = strlen($characters) - 1; // Counting the strlen each time, possibly 2000 times, is a waste of resources. (- 1) to remove you blank character errors.
  38.   $rString = ''; //  The return String. Declare before manipulating it, otherwise it will throw Warning Notice
  39.   for($i=0; $i<$length;++$i){
  40.     $rString .= $characters{mt_rand(0,($chrLen))}; // {} not [] -> [] are for arrays. PHP will process it properly now, but it won't in the future.
  41.   }
  42.   return $rString;
  43. }
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement