【问题标题】:Replacing every number in a string with a random char用随机字符替换字符串中的每个数字
【发布时间】:2017-08-06 13:36:19
【问题描述】:

我想用另一个随机字符替换 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)

【问题讨论】:

  • 我想不出任何方法可以在没有循环的情况下获得一串随机字符。为什么不想使用循环? (只是我,还是有时似乎有人告诉新程序员循环不好?)
  • 并不是说循环不好,只是似乎用正则表达式或类似的东西可以做得更干净

标签: php string random numbers


【解决方案1】:

你可以使用preg_replace_callback()

$str = 'ABC123EFG';

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

它会输出如下内容:

ABCcbrEFG

如果您需要大写值,可以将97122 更改为它们的ASCII 等效值,将64 更改为90

【讨论】:

  • 有没有办法在 python 中做到这一点?
【解决方案2】:

您可以使用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));

【讨论】:

  • array_flip(range('A', 'Z'))?
猜你喜欢
  • 2017-05-20
  • 2021-05-18
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多