PHP: how to add random character to string in random position

How can I add one random character (0-9 or az or - or _) at a random place in the string.

I can get a random position as follows:

$random_position = rand(0,5); 

Now How can I get a random number (0 to 9) OR a random character (a to z) OR (-) OR (_)

and finally, how can I add a character to the above line in the above random position.

For example, the following line:

 $string = "abc123"; $random_position = 2; $random_char = "_"; 

new line should be:

 "a_bc123" 
+4
source share
5 answers
 $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; 
+4
source

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; ?> 
+1
source
 $string = 'abc123'; $chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_'; $new_string = substr_replace( $string, $chars[rand(0, strlen($chars)-1)], rand(0, strlen($string)-1), 0 ); 
+1
source
 // 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 
0
source

get the string length:

 $string_length = strlen($string);//getting the length of the string your working with $random_position = 2;//generate random position 

generates a "random" character:

 $characters = "abcd..xyz012...89-_";//obviously instead of the ... fill in all the characters - i was just lazy. 

getting a random character from a 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 

splitting a string into two parts:

 $first_part = substr($string, 0, $random_position); $second_part = substr($string, $random_position, $string_length); 

add random character:

 $first_part .= $random_char; 

merging two back:

 $new_string = $first_part.$second_part; 

This may not be the best way, but I think he should do it ...

0
source

All Articles