Forum Moderators: coopster

Message Too Old, No Replies

Creating a random string of alpha characters

         

ayushchd

4:36 pm on Aug 7, 2007 (gmt 0)

10+ Year Member



How can i generate a random string that contains only alphabets?

d40sithui

5:19 pm on Aug 7, 2007 (gmt 0)

10+ Year Member



i dont know if there are any speficic php functions to do just this. but one way is to first create an array of the 26 letters.
$letters = array('a', 'b', ...);

then use rand(0,25) to pick out each letter until your string is full.

dreamcatcher

6:43 pm on Aug 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can easily create an array of letters using range [uk2.php.net].

$letters = range('a','z');

Then for random string, loop and use rand as mentioned by d40sithui.

$howmany = '20';
$string = '';

for ($i=0; $i<$howmany; $i++)
{
$string .= $letters[rand(0,25)];
}

echo $string;

dc

jatar_k

6:59 pm on Aug 7, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



another option using some of the above

$howmany = '20'; 
$newpass = '';
for ($i = 0; $i < $howmany; $i++) {
$randval = rand(97,122);
$newpass .= chr($randval);
}
echo $newpass;

or how about numbers and letters

$howmany = '20'; 
$newpass = '';
for ($i = 0; $i < $howmany; $i++) {
$randval = rand(48,83);
if ($randval > 57) { $randval = $randval + 39; }
$newpass .= chr($randval);
}
}
echo $newpass;

mooger35

9:15 pm on Aug 7, 2007 (gmt 0)

10+ Year Member



for numbers, small case and capitals:

$number = 20;
$newpass = '';

for($i = 0; $i < $number; $i++){
$randval = rand(48,109);
if($randval > 57 && $randval < 84) {$randval = $randval + 7;}
if($randval > 83) {$randval = $randval + 13;}
$newpass .= chr($randval);
}

echo $newpass;

daljitS

9:51 am on Aug 8, 2007 (gmt 0)

10+ Year Member



try this one too

$random_string_len = 10;
$source = "23456789"; //no 1
$source .= "abcdefghijkmnopqrstuvwxyz"; //no small L (l) because of its resemblance with 1
$source .= "ABCDEFGHJKLMNPQRSTUVWXYZ"; //no I because of resemblance to 1

srand ((double) microtime() * 1000000);
$result = '';

while ( $random_string_len )
{
$result .= substr($source, rand( 0, strlen( $source )), 1);
$random_string_len--;
}
echo $result;

mooger35

8:25 pm on Aug 8, 2007 (gmt 0)

10+ Year Member



Doesn't this:

$result .= substr($source, rand( 0, strlen( $source )), 1);

have to be this:

$result .= substr($source, rand( 0, strlen( $source )-1), 1);

dreamcatcher

2:03 pm on Aug 9, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or how about:

$chars = 25;

echo substr(md5(uniqid(rand(),1)),3,$chars);

dc

whoisgregg

4:49 pm on Aug 9, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or how about:

$length = 6;
$string = 'abcdefghijklmnopqrstuvwxyz';
$password = substr( str_shuffle($string), 0, $length );