Fill the remainder of a string with blank spaces - php

I have a string with, for example, 32 characters. For first, i want to establish that the string have max 32 characters and i want add blank spaces if characters is only, for example, 9.
Example:
ABCDEFGHI ---> 9 characters
I want this:
ABCDEFGHI_______________________ ---> 9 characters + 23 blank spaces added automatically.

The function you are looking for is str_pad.
http://php.net/manual/de/function.str-pad.php
$str = 'ABCDEFGHI';
$longstr = str_pad($str, 32);
The default pad string already is blank spaces.
As your maximum length should be 32 and str_pad won't take any action when the string is longer than 32 characters you might want to shorten it down using substr then:
http://de.php.net/manual/de/function.substr.php
$result = substr($longstr, 0, 32);
This again won't take any action if your string is exactly 32 characters long, so you always end up with a 32 characters string in $result now.

Use str_pad:
str_pad('ABCDEFGHI', 32);

Use str_pad function:
$result = str_pad($input, 32, " ");

you need str_pad
$padded = str_pad($in,32,' ');
You can have left or right padded, tons of options, check them all out here
If the input exceeds 32 chars, no action is taken, but that's an easy check to implement:
if (strlen($padded) > 32)
{
throw new Exception($padded.' is too long');//or some other action
}

If you want to do more customization inside the function you could use this
function fill($input, $length, $filler = ' ')
{
$len = strlen($input);
$diff = $length - $len;
if($diff > 0)
{
for ($i = 0; $i < $diff; $i++)
{
$input = $input . $filler;
}
}
return substr($input, 0, $length);
}

for($i=0;$i<(32-strlen($your_string));$i++)
{
$new_string.=$your_string.' '
}
hope that would be helpful for you

$str = "ABCDEFGHI";
for ($i = 0; $i < 23; $i++) {
$str .= " ";
}
This is what You want?
When saw other comments, then that will be the best solution.

Related

using chr + rand to generate a random character (A-Z)

I'm using the following to generate a random character from A-Z, but it's occasionally generating the # symbol. Any idea how to prevent this? Maybe the character range is incorrect?
$letter = chr(64+rand(0,26));
Use this it's easier.
Upper Case
$letter = chr(rand(65,90));
Lowercase
$letter = chr(rand(97,122));
ascii chart
The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.
function izrand($length = 32) {
$random_string="";
while(strlen($random_string)<$length && $length > 0) {
$randnum = mt_rand(0,61);
$random_string .= ($randnum < 10) ?
chr($randnum+48) : ($randnum < 36 ?
chr($randnum+55) : $randnum+61);
}
return $random_string;
}
update: 12/19/2015
Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add
the second paramater as true.
Example Usage
$randomNumber = izrand(32, true); // generates 32 digit number as string
$randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string
Typecast to Integer
If you want to typecast the number to integer, simply do this after you
generate the number. NOTE: This will drop any leading zeros if they exist.
$randomNumber = (int) $randomNumber;
izrand() v2
function izrand($length = 32, $numeric = false) {
$random_string = "";
while(strlen($random_string)<$length && $length > 0) {
if($numeric === false) {
$randnum = mt_rand(0,61);
$random_string .= ($randnum < 10) ?
chr($randnum+48) : ($randnum < 36 ?
chr($randnum+55) : chr($randnum+61));
} else {
$randnum = mt_rand(0,9);
$random_string .= chr($randnum+48);
}
}
return $random_string;
}
ASCII code 64 is #. You want to start at 65, which is A. Also, PHP's rand generates a number from min to max inclusive: you should set it to 25 so the biggest character you get is 90 (Z).
$letter = chr(65 + rand(0, 25));
$range = range('A', 'Z');
$index = array_rand($range);
echo $range[$index];
You could use, given you could generate from a-Z:
$range = array_merge(range('A', 'Z'),range('a', 'z'));
$index = array_rand($range, 1);
echo $range[$index];
The below code will generate an alphanumric string of 2 letters and 3 digits.
$string = strtoupper(chr(rand(65, 90)) . chr(rand(65, 90)) . rand(100, 999));
echo $string;

PHP: Generating random string with both suffix and prefix as capital letters

Hie guys i want to create a random string of numbers where there is a fixed letter B at the beginning and a set of eight integers ending with any random letter, like for example B07224081A where A and the other numbers are random. This string should be unique. How can I do this?
Do you mean something like this?
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];
$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case
The more characters - the greater chance to generate unique string.
I think that's much better method to use uniqid() since it's based on miliseconds. Uniqueness of generated string is guaranteed.
This should work for you.
$randomString = "B";
for ($i = 0; $i < 9; $i++) {
if ($i < 8) {
$randomString.=rand(0,9);
}
if ($i == 8) {
$randomString.=chr(rand(65,90));
}
}
echo $randomString;

Increment through A-Za-z0-9 in expanding string with PHP

I'm trying to generate strings in PHP with a group of valid characters, cycling through them and appending an extra character on the end of the string, until maximum length is reached. For example, desired output:
a,b,c,d,e,f,aa,ab,ac,ad,ae,af,ba,bb,bc,bd,be,bf,ca,cb..etc
This is my PHP function so far:
<?php
$chars = Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z',
'1','2','3','4','5','6','7','8','9','0');
$maxlen = 10;
$input = $chars[0];
while (1):
echo buildInput($maxlen, $chars, $input) . "\n";
endwhile;
function buildInput($maxlen, $chars, $previous)
{
if (array_search(substr($previous, -1), $chars) == sizeof($chars) - 1):
// end of input cycle reached, add another character
$previous = $previous . $chars[0];
endif;
if (strlen($previous) > $maxlen):
die('Max length reached');
endif;
// Remove last character, and append incremented char
$input = substr($previous, 0, -1);
$input = $input . $chars[array_search(substr($previous, -1), $chars)+1];
return $input;
}
?>
It only increments the last character of the string which gets to 0, then appends 'a' and starts over but without trying all the other possible permutations.
Could someone help me with a better method?
Is this the kind of thing you want?
<?php
$chars = array('a','b','c');
$max_length = 3;
function build($base_arr, $ctr) {
global $chars;
global $max_length;
$combos = array();
foreach ($base_arr as $base) {
foreach ($chars as $char) {
echo $base, $char, '<br />';
$combos[] = $base.$char;
}
}
if ($ctr < $max_length) {
build($combos, $ctr + 1);
}
}
foreach ($chars as $char) {
echo $char, '<br />';
}
build($chars, 2);
?>
It'll give you: a, b, c, aa, ab, ac, ba, bb, bc, ca, cb, cc, ..., bcc, caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc.
Your array is so large, though, that using this method on it would take up way too much memory to work. Out of 62 characters (A-Z, a-z, 0-9), the number of possible 10-character permutations is 8.4 x 10^17; so hopefully, you'll be able to find a more efficient method or figure out a way to get the result you want without having to cycle through such a large array. I hope you find what you're looking for!
If you limit yourself to 0-9,a-z (only lower case), then you could use base_convert for this and do it in one line:
for($i = 0; $i < 1000; $i++) echo base_convert($i, 10, 36) . '<br/>';
Here's a demo.
This will print 200 letters: a,b,c,d,...,aa,...,cq
The buildString function will build our string from the least significant number (right) to the most significant (left). By performing a modulus division, you will find the array position of the next character. Add this character to the front of your string, and divide
your number by the size of your array (which is the base number in your character based number system), ignoring the rest.
To explain the method using our normal 10-based number system and the input of 123, you would simply pick the last digit, 3, divide the input by 10, pick the last digit 2, divide the input by 10, pick the last digit 1, divide the input by 10. The input is now 0 and your output is ready...
$chars = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J'
,'K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','1','2','3','4'
,'5','6','7','8','9','0');
$numChars = count($chars);
// Output numbers from 1 to 200 (a to cq)
for($i = 1; $i <= 200; $i++) {
echo buildString($i).'<br>';
}
// Will also work fine for large numbers - output "dxSA"
echo buildString(1000000).'<br>';
function buildString($int) {
global $chars;
global $numChars;
$output = '';
while($int) {
$output = $chars[($int-1) % $numChars] . $output;
$int = floor(($int-1) / $numChars);
}
return $output;
}
If you have access to gmp extension and PHP 5.3.2+ this will work for the charset you specified:
$result = strtr(
gmp_strval(gmp_init($i, 10), 62),
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
);

Cutting down a length of a PHP string and inserting an ellipses

I want to turn a long string like reallyreallyreallyreallyreallylongfilename into something like reallyreallyre...yreallyreally.
Basically, find the middle of the string and replace everything there until the length of the string is < 30 characters including an ellipses to signify there has been parts of the string replaced.
This is my code where I have tried this:
function cutString($input, $maxLen = 30)
{
if(strlen($input) < $maxLen)
{
return $input;
}
$midPoint = floor(strlen($input) / 2);
$startPoint = $midPoint - 1;
return substr_replace($input, '...', $startPoint, 3);
}
It finds the center of the string and replaces a character either side with . but the thing is I can't work out how to make it cut it down to 30 characters, or whatever $maxLen is.
Hopefully you understand my question, I don't think I did a very good job at explaining it 8)
Thanks.
How about:
if (strlen($input) > $maxLen) {
$characters = floor($maxLen / 2);
return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}

How to create a random string using PHP?

I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:
Original string, 9 chars
$string = 'abcdefghi';
Example random string limiting to 6 chars
$string = 'ibfeca';
UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.
UPDATE: The function should generate any amount of chars as required.
Please comment the parts if you reply.
If you want to allow repetitive occurences of characters, you can use this function:
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
{
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
The basic algorithm is to generate <length> times a random number between 0 and <number of characters> − 1 we use as index to pick a character from our set and concatenate those characters. The 0 and <number of characters> − 1 bounds represent the bounds of the $charset string as the first character is addressed with $charset[0] and the last with $charset[count($charset) - 1].
Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:
function get_random_string($valid_chars, $length)
{
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
To call this function with your example data, you'd call it something like:
$original_string = 'abcdefghi';
$random_string = get_random_string($original_string, 6);
Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of 'AAAB', it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.
My favorite:
echo substr(md5(rand()), 0, 7);
So, let me start off by saying USE A LIBRARY. Many exist:
RandomCompat
RandomLib
SecurityMultiTool
The core of the problem is almost every answer in this page is susceptible to attack. mt_rand(), rand(), lcg_value() and uniqid() are all vulnerable to attack.
A good system will use /dev/urandom from the filesystem, or mcrypt_create_iv() (with MCRYPT_DEV_URANDOM) or openssl_pseudo_random_bytes(). Which all of the above do. PHP 7 will come with two new functions random_bytes($len) and random_int($min, $max) that are also safe.
Be aware that most of those functions (except random_int()) return "raw strings" meaning they can contain any ASCII character from 0 - 255. If you want a printable string, I'd suggest running the result through base64_encode().
function generate_random_string($name_length = 8) {
$alpha_numeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return substr(str_shuffle(str_repeat($alpha_numeric, $name_length)), 0, $name_length);
}
Updated the code as per mzhang's great suggestion in the comments below.
A better and updated version of #taskamiski's excellent answer:
Better version, using mt_rand() instead of rand():
echo md5(mt_rand()); // 32 char string = 128bit
Even better, for longer strings, using the hash() function that allows to select hashing algorithmns:
echo hash('sha256', mt_rand()); // 64 char string
echo hash('sha512', mt_rand()); // 128 char string
If you want to cut the result down to let's say 50 chars, do it like this:
echo substr(hash('sha256', mt_rand()), 0, 50); // 50 char string
Joining characters at the end should be more efficient that repeated string concatenation.
Edit #1: Added option to avoid character repetition.
Edit #2: Throws exception to avoid getting into infinite loop if $norepeat is selected and $len is greater than the charset to pick from.
Edit #3: Uses array keys to store picked random characters when $norepeat is selected, as associative array key lookup is faster than linearly searching the array.
function rand_str($len, $norepeat = true)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$max = strlen($chars) - 1;
if ($norepeat && len > $max + 1) {
throw new Exception("Non repetitive random string can't be longer than charset");
}
$rand_chars = array();
while ($len) {
$picked = $chars[mt_rand(0, $max)];
if ($norepeat) {
if (!array_key_exists($picked, $rand_chars)) {
$rand_chars[$picked] = true;
$len--;
}
}
else {
$rand_chars[] = $picked;
$len--;
}
}
return implode('', $norepeat ? array_keys($rand_chars) : $rand_chars);
}
this will generate random string
function generateRandomString($length=10) {
$original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
$original_string = implode("", $original_string);
return substr(str_shuffle($original_string), 0, $length);
}
echo generateRandomString(6);
I think I will add my contribution here as well.
function random_string($length) {
$bytes_1 = openssl_random_pseudo_bytes($length);
$hex_1 = bin2hex($bytes_1);
$random_numbers = substr(sha1(rand()), 0, $length);
$bytes_2 = openssl_random_pseudo_bytes($length);
$hex_2 = bin2hex($bytes_2);
$combined_chars = $hex_1 . $random_numbers . $hex_2;
$chars_crypted = hash('sha512', $combined_chars);
return $chars_crypted;
}
Thanks
Most aspects of this have already been discussed, but i'd recommend a slight update:
If you are using this for retail usage, I would avoid the domain
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
and instead use:
ABCDEFGHJKMNPQRSTUVWXY3456789
Granted, you end up with far fewer characters, but it saves a great deal of hassle, as customers cannot mistake 0 for O, or 1 for l or 2 for Z. Also, you can do an UPPER on the input and customers can then enter upper or lower case letters -- that is also sometimes confusing since they can look similar.
What do you need a random string for?
Is this going to be used for anything remotely analogous to a password?
If your random string requires any security properties at all, you should use PHP 7's random_int() function instead of all the insecure mt_rand() answers in this thread.
/**
* Generate a random string
*
* #link https://paragonie.com/b/JvICXzh_jhLyt4y3
*
* #param int $length - How long should our random string be?
* #param string $charset - A string of all possible characters to choose from
* #return string
*/
function random_str($length = 32, $charset = 'abcdefghijklmnopqrstuvwxyz')
{
// Type checks:
if (!is_numeric($length)) {
throw new InvalidArgumentException(
'random_str - Argument 1 - expected an integer'
);
}
if (!is_string($charset)) {
throw new InvalidArgumentException(
'random_str - Argument 2 - expected a string'
);
}
if ($length < 1) {
// Just return an empty string. Any value < 1 is meaningless.
return '';
}
// This is the maximum index for all of the characters in the string $charset
$charset_max = strlen($charset) - 1;
if ($charset_max < 1) {
// Avoid letting users do: random_str($int, 'a'); -> 'aaaaa...'
throw new LogicException(
'random_str - Argument 2 - expected a string at least 2 characters long'
);
}
// Now that we have good data, this is the meat of our function:
$random_str = '';
for ($i = 0; $i < $length; ++$i) {
$r = random_int(0, $charset_max);
$random_str .= $charset[$r];
}
return $random_str;
}
If you aren't on PHP 7 yet (which is probably the case, as it hasn't been released as of this writing), then you'll want paragonie/random_compat, which is a userland implementation of random_bytes() and random_int() for PHP 5 projects.
For security contexts, always use random_int(), not rand(), mt_rand(), etc. See ircmaxell's answer as well.
built on top of https://stackoverflow.com/a/853898/533426
but with php 7 cryptographically secure random function and lower AND upper case alphabet
function random($length = 8){
$valid_chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = random_int(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
//example output XjdXHakZ, yBG8hpZG, L6jg4FpK
// #author http://codeascraft.etsy.com/2012/07/19/better-random-numbers-in-php-using-devurandom/
function devurandom_rand($min = 0, $max = 0x7FFFFFFF)
{
$diff = $max - $min;
if ($diff < 0 || $diff > 0x7FFFFFFF) {
throw new RuntimeException('Bad range');
}
$bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
if ($bytes === false || strlen($bytes) != 4) {
throw new RuntimeException('Unable to get 4 bytes');
}
$ary = unpack('Nint', $bytes);
$val = $ary['int'] & 0x7FFFFFFF; // 32-bit safe
$fp = (float) $val / 2147483647.0; // convert to [0,1]
return round($fp * $diff) + $min;
}
function build_token($length = 60, $characters_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
$map_length = mb_strlen($characters_map)-1;
$token = '';
while ($length--) {
$token .= mb_substr($characters_map, devurandom_rand(0,$map_length),1);
}
return $token;
}
This will work only in UNIX environment where PHP is compiled with mcrypt.
Do you want to create your password by a random permutation of the original letters? Should it just contain unique characters?
Use rand to choose random letters by index.
This is an old question but I want try to post my solution... I always use this my function to generate a custom random alphanumeric string...
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = mt_rand(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
$test = random_alphanumeric(50); // 50 characters
echo $test;
?>
test: UFOruSSTCPIqxTRIIMTRkqjOGidcVlhYaS9gtwttxglheVugFM
if you need two or more unique strings you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
$string_1: tMYicqLCHEvENwYbMUUVGTfkROxKIekEB2YXx5FHyVByp3mlJO
$string_2: XdMNJYpMlFRKFDlF6GhVn6jsBVNQ1BCCevj8yK2niFOgpDI2MU
I hope this help.
echo substr(bin2hex(random_bytes(14)), 0, $length);
this code gets a random bytes, that are converted from binary to hexadecimal, and then takes a substring of this hexadecimal string, as long you puts in $length variable
Try this
Simple enough!
function RandomFromCharset($charset,$length)
{
$characters = $charset; // your existing charset / defined string
$charactersLength = strlen($characters);
$random_from_charset = '';
for ($i = 0; $i < $length; $i++)
{
$random_from_charset.= $characters[rand(0, $charactersLength - 1)];
}
return random_from_charset;
}
Call the function as follows
RandomFromCharset($charset,$length);
where $length will be length of random string you want (this can be predefined also in the function as RandomFromCharset(charset,$length=10) ) to generate and $charset will be your existing string to which you want to restrict the characters.
One approach is to generate an md5 from a random number and extract the number of characters you want:
<?php
$random = substr(md5(mt_rand()), 0, 7);
echo $random;
?>
mt_rand will generate a random number, md5 will create a 32 character string (containing both letters and numbers) and, in this example, we're extracting the first 7 characters of text.
you could make an array of characters then use rand() to pick a letter from the array and added it to a string.
$letters = array( [0] => 'a' [1] => 'b' [2] => 'c' [3] => 'd' ... [25] = 'z');
$lengthOfString = 10;
$str = '';
while( $lengthOfString-- )
{
$str .= $letters[rand(0,25)];
}
echo $str;
*note that this does allow repeat characters
This builds on Gumbo's solution by adding functionality to list a set of characters to be skipped in the base character set. The random string selects characters from $base_charset which do not also appear in $skip_charset.
/* Make a random string of length using characters from $charset, excluding $skip_chars.
* #param length (integer) length of return value
* #param skip_chars (string) characters to be excluded from $charset
* #param charset (string) characters of posibilities for characters in return val
* #return (string) random string of length $length */
function rand_string(
$length,
$skip_charset = '',
$base_charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'){
$skip_len = strlen($skip_charset);
for ($i = 0; $i<$skip_len; $i++){
$base_charset = str_replace($skip_charset[$i], '', $base_charset);
}
cvar_dump($base_charset, '$base_charset after replace');
$str = '';
$count = strlen($base_charset);
while ($length--) {
$str .= $base_charset[mt_rand(0, $count - 1)];
}
return $str;
}
Here are some usage examples. The first two examples use the default value for $base_charset. The last example explicitly defines $base_charset.
echo rand_string(15, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
// 470620078953298
echo rand_string(8, 'abcdefghijklmnopqrstuvwxyz0123456789');
// UKLIHOTFSUZMFPU
echo rand_string(15, 'def', 'abcdef');
// cbcbbccbabccaba
well, I was looking for a solution, and I kindda used #Chad Birch's solution merged with #Gumbo's one. This is what I came up with:
function get_random_string($length, $valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456790!·$%&/()=?¿¡',.-;:+*`+´ç")
{
$random_string = "";
$num_valid_chars = strlen($valid_chars);
for ($i = 0; $i < $length; $i++, $random_string .= $valid_chars[mt_rand(1, $num_valid_chars)-1]);
return $random_string;
}
I think comments are pretty much unnecesary since the answers I used to build up this one are already thoroughly commented. Cheers!
If you're not concerned about time, memory, or cpu efficiency, and if your system can handle it, why not give this algorithm a try?!
function randStr($len, $charset = 'abcdABCD0123') {
$out = '';
$str = array();
for ($i = 0; $i < PHP_INT_MAX; $i++) {
$str[$i] = $charset;
shuffle($str);
$charset .= implode($charset, $str);
$charset = str_shuffle($charset);
}
$str = array_flip($str);
$str = array_keys($str);
for ($i = 0; $i < PHP_INT_MAX; $i++) {
shuffle($str);
}
$str = implode('', $str);
for ($i = 0; $i < strlen($str); $i++) {
$index = mt_rand(1, strlen($str));
$out .= $str[$index - 1];
}
for ($i = 0; $i < PHP_INT_MAX; $i++) {
$out = str_shuffle($out);
}
return substr($out, 0, $len);
}
Maybe this will read better if it uses recursion, but I'm not sure if PHP uses tail recursion or not...

Categories