Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Cleaned up and sped up.
- 1000 interations of producing 2000 char string:
- Original - 4.1486458778381 seconds
- This rewrite - 2.3620591163635
- %43 percent improvement
- */
- function cw_randchar( $length=NULL, $case=NULL, $spaces=false){
- // 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.
- if(!is_numeric($length)){
- $temp_length = $length;
- if(strpos($temp_length,',') !== false){ // strpos is faster/less resource intensive as strstr
- $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.
- }
- $length = (is_numeric($temp_length))? $temp_length : strlen($length);
- }
- $length = (int)$length;
- if($length === 0){
- $length = 8;
- }else if($length > 2000){
- $length = 2000;
- }
- // 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;
- if(stripos($case,'lower') !== false){
- $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
- }else if(stripos($case, 'upper') !== false){
- $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- }else{
- $characters = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- }
- if($spaces){
- $characters .= ($case)? str_pad('',16,' ') : str_pad('',8,' ');
- }
- // No need for the is_bool() check as default is false
- $chrLen = strlen($characters) - 1; // Counting the strlen each time, possibly 2000 times, is a waste of resources. (- 1) to remove you blank character errors.
- $rString = ''; // The return String. Declare before manipulating it, otherwise it will throw Warning Notice
- for($i=0; $i<$length;++$i){
- $rString .= $characters{mt_rand(0,($chrLen))}; // {} not [] -> [] are for arrays. PHP will process it properly now, but it won't in the future.
- }
- return $rString;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement