I have a string from which I want to replace only the odd positions by a random digit.
For Example, the string is '123456'
. Now the output I want is '528496'
;
Note that the digits 1,3,5 in odd positions are replaced by random digits 5,8,9.
I know how to do this using a PHP loop but was wondering if it could be done using a regex.
I found the following two relevant solutions on the web but still wasn't able to make it work.
Solution 1
echo preg_replace('/(.)./', '$1 ', $str);
Solution 2
echo preg_replace_callback('/\d/', function() {
return chr(mt_rand(97, 122));
}, $str);
PS: I tried to comment on these questions but since I just have reputation of 5 I was not able to :(