用随机字符替换字符串中的每个数字
问题描述:
我想用另一个随机字符替换字符串ABC123EFG
中的每个数字。
我的想法是用$str
中的所有数字生成一个随机字符串,并将每个数字替换为$array[count_of_the_digit]
,有没有办法在没有for循环的情况下执行此操作,例如使用正则表达式?用随机字符替换字符串中的每个数字
$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)
答
你可以使用preg_replace_callback()
$str = 'ABC123EFG';
echo preg_replace_callback('/\d/', function(){
return chr(mt_rand(97, 122));
}, $str);
这将输出类似:
ABCcbrEFG
如果你想大写值,你可以改变97
和122
其对应的ASCII码的64
到90
。
答
您可以使用preg_replace_callback调用返回值为替换值的函数。下面是一个你想要的例子:
<?php
function preg_replace_random_array($string, $pattern, $replace){
//perform replacement
$string = preg_replace_callback($pattern, function($m) use ($replace){
//return a random value from $replace
return $replace[array_rand($replace)];
}, $string);
return $string;
}
$string = 'test123asdf';
//I pass in a pattern so this can be used for anything, not just numbers.
$pattern = '/\d/';
//I pass in an array, not a string, so that the replacement doesn't have to
//be a single character. It could be any string/number value including words.
$replace = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
var_dump(preg_replace_random_array($string, $pattern, $replace));
我想不出任何你会得到一串没有循环的随机字符串。你为什么不想使用循环? (这是否只是我,还是有时似乎有人告诉新的程序员,循环是坏的?) – alanlittle
它不是循环是坏的,它似乎可以用正则表达式或类似的东西干净地完成 – nn3112337