Home:ALL Converter>PHP: how to add a random character in a string at random position

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

Ask Time:2011-06-28T15:41:01         Author:sunjie

Json Formatter

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"

Author:sunjie,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/6503176/php-how-to-add-a-random-character-in-a-string-at-random-position
Mike :

$string = 'abc123';\n$chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_';\n$new_string = substr_replace(\n $string,\n $chars[rand(0, strlen($chars)-1)],\n rand(0, strlen($string)-1),\n 0\n);\n",
2011-06-28T08:08:44
YonoRan :

get the string length:\n\n$string_length = strlen($string);//getting the length of the string your working with\n$random_position = 2;//generate random position\n\n\ngenerate the \"random\" character:\n\n$characters = \"abcd..xyz012...89-_\";//obviously instead of the ... fill in all the characters - i was just lazy.\n\n\ngetting a random character out of the character string:\n\n$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\n\n\nbreaking the string into 2 parts:\n\n$first_part = substr($string, 0, $random_position);\n$second_part = substr($string, $random_position, $string_length);\n\n\nadding the random character:\n\n$first_part .= $random_char;\n\n\ncombining the two back together:\n\n$new_string = $first_part.$second_part;\n\n\nthis may not be the best way, but I think it should do it...",
2011-06-28T07:55:02
khattam :

$string = \"abc123\";\n$random_position = rand(0,strlen($string)-1);\n$chars = \"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789-_\";\n$random_char = $chars[rand(0,strlen($chars)-1)];\n$newString = substr($string,0,$random_position).$random_char.substr($string,$random_position);\necho $newString;\n",
2011-06-28T07:48:29
rrapuya :

try something like this\n\n<?php \n\n $orig_string = \"abc123\";\n $upper =strlen($orig_string);\n $random_position = rand(0,$upper);\n $int = rand(0,51);\n $a_z = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n $rand_char = $a_z[$int];\n\n\n $newstring=substr_replace($orig_string, $rand_char, $random_position, 0);\n\n echo 'original-> ' .$orig_string.'<br>';\n echo 'random-> ' .$newstring;\n?>\n",
2011-06-28T07:53:00
yy