dongli8722 2019-08-10 18:57
浏览 456

如何使用Laravel Faker在最小和最大字符数之间生成随机字符串

I'm looking for a way to generate random string between min and max number of characters using laravel Faker. I have to create random strings between 4 and 20 characters. This method str_random will generate exactly 20 characters, but how to specify min number of characters?

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => str_random(20),
    ];
});

Updated: I'm using the following code now as a workaround:

'name' => substr($faker->name(), 0, rand(4, 20))
</div>
  • 写回答

1条回答 默认 最新

  • dsbruqxgt820011351 2019-08-11 02:21
    关注

    You could use regexify and and this let's you control what characters could be in the randomly generated string like this:

    <?php
    
    use Faker\Generator as Faker;
    
    $factory->define(App\User::class, function (Faker $faker) {
        return [
            'name' => $faker->regexify('[A-Za-z0-9]{' . mt_rand(4, 20) . '}'),
        ];
    });
    

    Another option is $faker->realText(mt_rand(4, 20))

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?