There's a string, containing characters [a-zA-Z0-9]
. This should be 26 * 2 + 10 = 62 possibilities in one character and 62^2 in two. What is the preferred way to increment a value of such a string, so that 'aA', becomes 'aB', etc.? Is there any built-in stuff in PHP, that can help?
I know you can increment a string, but that's only lowercase letters. Essentially, the result should go from 'a' to 'aa' in 61 increments.
<? php $length = 4; $id = ''; for ($i=0;$i<$length;$i++){ $id . = rand(1, 9); } echo $id; ?>
This can be carried out using the simple increment (++) operator just like in numbers. The only point of difference being decrement (–) operator doesn't work the same in letters as it does in numbers.
A ctype_alnum() function in PHP used to check all characters of given string/text are alphanumeric or not. If all characters are alphanumeric then return TRUE, otherwise return FALSE. Parameters Used: $text : It is a mandatory parameter which specifies the string.
Try this function:
<?php
function increment(&$string){
$last_char=substr($string,-1);
$rest=substr($string, 0, -1);
switch ($last_char) {
case '':
$next= 'a';
break;
case 'z':
$next= 'A';
break;
case 'Z':
$next= '0';
break;
case '9':
increment($rest);
$next= 'a';
break;
default:
$next= ++$last_char;
}
$string=$rest.$next;
}
//sample
$string='a';
for($i=1;$i<=128;$i++){
echo $string."<br>";
increment($string);
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With