[英]Replace odd positions in string with a random digit in php
I have a string from which I want to replace only the odd positions by a random digit.我有一个字符串,我只想用随机数字替换其中的奇数位置。
For Example, the string is '123456'
.例如,字符串是
'123456'
。 Now the output I want is '528496'
;现在我想要的输出是
'528496'
; Note that the digits 1,3,5 in odd positions are replaced by random digits 5,8,9.请注意,奇数位置的数字 1、3、5 被随机数字 5、8、9 替换。
I know how to do this using a PHP loop but was wondering if it could be done using a regex.我知道如何使用 PHP 循环来做到这一点,但想知道是否可以使用正则表达式来完成。
I found the following two relevant solutions on the web but still wasn't able to make it work.我在网上找到了以下两个相关的解决方案,但仍然无法使其工作。
Solution 1解决方案1
echo preg_replace('/(.)./', '$1 ', $str);
Solution 2解决方案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 :( PS:我试图对这些问题发表评论,但由于我只有 5 的声誉,所以我无法 :(
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.如果您的 PHP 版本低于 7.1,则不应使用
rand()
因为它是一个无法正常工作的坏函数。 Use mt_rand(0, 9)
instead.使用
mt_rand(0, 9)
代替。
If you need the random numbers to be cryptographically secure, use random_int(0, 9)
instead.如果您需要随机数加密安全,请改用
random_int(0, 9)
。 This function is available in PHP 7.这个函数在 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 )代码:( PHP7.4 演示)
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'
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.