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 :(
preg_replace_callback('/.(.)/s', function($m){ return chr(mt_rand(48, 57)) . $m[1]; }, '123456');
, see 3v4l.org/8dDmL – Wiktor Stribiżew Sep 7 '20 at 16:55chr()
, you can usemt_rand(0, 9)
. Starting with PHP 7.4 you can even write:echo preg_replace_callback('/.(.)/', fn($m) => rand(0,9) . $m[1], '123456');
– Casimir et Hippolyte Sep 7 '20 at 17:16