如何使用 Laravel Faker 生成随机字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49464984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:33:31  来源:igfitidea点击:

How to Generate Random String using Laravel Faker?

laravelfakerfake-repositories

提问by Vishal

is there any way or method to generate fake string using laravel faker ?

有什么方法或方法可以使用 laravel faker 生成假字符串吗?

like in laravel we generate string upto 20 chars..

就像在 Laravel 中我们生成最多 20 个字符的字符串..

 str_random(20);

回答by jedrzej.kurylo

Faker offers a couple of methods that let you replace placeholders in a given string with random characters:

Faker 提供了几种方法,让您可以用随机字符替换给定字符串中的占位符:

  • lexify- takes given string and replaces ? with random letters
  • asciify- takes given string and replaces * with random ascii characters
  • numerify- takes given string and replaces # with random digits
  • bothify- combines the lexify and numerify
  • lexify- 接受给定的字符串并替换 ? 带有随机字母
  • asciify- 接受给定的字符串并用随机的 ascii 字符替换 *
  • numerify- 获取给定的字符串并用随机数字替换 #
  • bothify- 结合词法和数字

You could try to use one of them, depending on the requirements you have for that random string you need. asciifyuses the largest set of characters as replacement so using that one makes most sense.

您可以尝试使用其中之一,具体取决于您对所需随机字符串的要求。asciify使用最大的一组字符作为替换,因此使用那个字符集最有意义。

The following will give you a random string of 20 ascii characters:

以下将为您提供20 个 ascii 字符随机字符串

$faker->asciify('********************')

回答by Matthias Schobner

Alternate for generate string without special chars.

替代生成没有特殊字符的字符串。

$faker->regexify('[A-Za-z0-9]{20}')

回答by Supun Praneeth

uze Faker\Provider\en_US\Text

使用Faker\Provider\en_US\Text

<?php

realText($maxNbChars = 200, $indexSize = 2) // "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied."