Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing every number in a string with a random char

I want to replace every number in a string like ABC123EFG with another random char.
My idea was to generate a random string with the number of all numbers in $str and replace every digit by $array[count_of_the_digit], is there any way to do this without a for-loop, for example with regex?

$count = preg_match_all('/[0-9]/', $str);
$randString = substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", $count)), 0, $count);
$randString = str_split($randString);
$str = preg_replace('/[0-9]+/', $randString[${n}], $str); // Kinda like this (obviously doesnt work)
like image 364
nn3112337 Avatar asked Dec 13 '25 13:12

nn3112337


1 Answers

You could use preg_replace_callback()

$str = 'ABC123EFG';

echo preg_replace_callback('/\d/', function(){
  return chr(mt_rand(97, 122));
}, $str);

It would output something like:

ABCcbrEFG

If you want upper case values, you can change 97 and 122 to their ASCII equivalent of 64 to 90.

like image 55
Xorifelse Avatar answered Dec 15 '25 02:12

Xorifelse