用随机字符替换字符串中的每个数字

时间:2017-03-15 16:55:29

标签: php string random numbers

我想用另一个随机字符替换像ABC123EFG这样的字符串中的每个数字 我的想法是生成一个随机字符串,其中包含$str中所有数字的数字,并用$array[count_of_the_digit]替换每个数字,有没有办法在没有for循环的情况下执行此操作,例如使用正则表达式?< / p>

$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)

2 个答案:

答案 0 :(得分:2)

您可以使用preg_replace_callback()

$str = 'ABC123EFG';

echo preg_replace_callback('/\d/', function(){
  return chr(mt_rand(97, 122));
}, $str);

它会输出如下内容:

ABCcbrEFG

如果您想要大写值,可以将97122更改为等效于6490的ASCII。

答案 1 :(得分:0)

您可以使用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));
相关问题