Reputation: 2053
How can i add a single random character (0-9 or a-z or - or _) at a random place in a string.
I can get the random position by following:
$random_position = rand(0,5);
Now How can i get a random number ( 0 to 9 ) OR random character (a to z) OR (-) OR (_)
and finally how i can add character to the above string in the above random position.
For example following is string:
$string = "abc123";
$random_position = 2;
$random_char = "_";
the new string should be:
"a_bc123"
Upvotes: 8
Views: 7531
Reputation: 45589
// map of characters
$map = '0123456789abcdefghijklmnopqrstuvwxyz-_';
// draw a random character from the map
$random_char_posotion = rand(0, strlen($map)-1); // say 2?
$random_char = $map[$random_char_posotion]; // 2
$str = 'abc123';
// draw a random position
$random_position = rand(0, strlen($str)-1); // say 3?
// inject the randomly drawn character
$str = substr($str, 0, $random_position).$random_char.substr($str,$random_position);
// output the result
echo $str; // output abc2123
Upvotes: 0
Reputation: 21659
$string = 'abc123';
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_';
$new_string = substr_replace(
$string,
$chars[rand(0, strlen($chars)-1)],
rand(0, strlen($string)-1),
0
);
Upvotes: 1
Reputation: 1728
get the string length:
$string_length = strlen($string);//getting the length of the string your working with
$random_position = 2;//generate random position
generate the "random" character:
$characters = "abcd..xyz012...89-_";//obviously instead of the ... fill in all the characters - i was just lazy.
getting a random character out of the character string:
$random_char = substr($characters, rand(0,strlen($characters)), 1);//if you know the length of $characters you can replace the strlen with the actual length
breaking the string into 2 parts:
$first_part = substr($string, 0, $random_position);
$second_part = substr($string, $random_position, $string_length);
adding the random character:
$first_part .= $random_char;
combining the two back together:
$new_string = $first_part.$second_part;
this may not be the best way, but I think it should do it...
Upvotes: 0
Reputation: 298
try something like this
<?php
$orig_string = "abc123";
$upper =strlen($orig_string);
$random_position = rand(0,$upper);
$int = rand(0,51);
$a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$rand_char = $a_z[$int];
$newstring=substr_replace($orig_string, $rand_char, $random_position, 0);
echo 'original-> ' .$orig_string.'<br>';
echo 'random-> ' .$newstring;
?>
Upvotes: 2
Reputation: 1174
$string = "abc123";
$random_position = rand(0,strlen($string)-1);
$chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789-_";
$random_char = $chars[rand(0,strlen($chars)-1)];
$newString = substr($string,0,$random_position).$random_char.substr($string,$random_position);
echo $newString;
Upvotes: 5