Replace odd positions in string with a random digit in php

Viewed 482

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 :(

2 Answers

Replace characters at odd index

echo preg_replace_callback('/.(.|$)/', function ($matches) {
    return rand(0, 9) . $matches[1];
}, $str);

Replace characters at even index

echo preg_replace_callback('/(.)./', function ($matches) {
    return $matches[1] . rand(0, 9);
}, $str);

Notes

If your PHP version is less than 7.1, you shouldn't use rand() as it was a bad function which didn't work properly. Use mt_rand(0, 9) instead.

If you need the random numbers to be cryptographically secure, use random_int(0, 9) instead. This function is available in PHP 7.

You can perform the replacements without referencing the matched string at all. Only keep the single character which must be replaced.

Code: (PHP7.4 Demo)

replace odd positions:

echo preg_replace_callback(
         '/^.|.\K./',
         fn() => rand(0,9),
         '1234567'
     );

replace even positions:

echo preg_replace_callback(
         '/.\K./',
         fn() => rand(0,9),
         '1234567'
     );
Related