Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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"
like image 894
sunjie Avatar asked Jun 28 '11 07:06

sunjie


2 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;
like image 163
khattam Avatar answered Oct 17 '22 08:10

khattam


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;
?>
like image 37
rrapuya Avatar answered Oct 17 '22 06:10

rrapuya