PHP生成随机英文用户名
我最近使用wordpress来撰写英文博客。我需要编造一些随机的英语用户名php随机生成英文名,以冒充访客发表评论。因为我不熟悉PHP(我从未学习过PHP),所以只能在百度和Google上找到方法。有3种方法:
1、随机字母数字组合方法
此方法的思想: 大写和小写26个字母+ 10个数字(0〜9)随机组合为6到10个字符串作为用户名,代码如下:
function random_user($len = 8) { $user = ''; $lchar = 0; $char = 0; for($i = 0; $i < $len; $i++) { while($char == $lchar) { $char = rand(48, 109); if($char > 57) $char += 7; if($char > 90) $char += 6; } $user .= chr($char); $lchar = $char; } return $user; }
调用方法(默认情况下会生成8个字符串):
<?php echo random_user();?>
产生的英文用户名如下:
4c3yXssf,6IG0bdfa,u5NDh5d3,spBhdgPn,49otf8ub,NE8zg2dS
缺点很明显: 不可靠php随机生成英文名,可读性差,而且一目了然它就是代码生成。
2、调用现成的API
这个想法也很简单。您可以直接调用可以生成用户数据的API。当然,您必须具有这样的API。我用Google搜索并找到了它:
直接以json格式返回用户的各种信息,包括: 姓名,个性,年龄,城市,电子邮件地址,头像等。这是返回的数据:
{"results":[ { "gender":"female", "name":{ "title":"miss", "first":"frida", "last":"christiansen" }, "location":{ "street":"2087 oddenvej", "city":"ulsted, hals", "state":"danmark", "postcode":33076 }, "email":"frida.christiansen@example.com", "login":{ "username":"brownostrich869", "password":"blacks", "salt":"hnroL361", "md5":"e77b5d194fa24307d94166fdb073489a", "sha1":"1f7c5119845d31071035ba786cfd1829ca4188de", "sha256":"37e202da9ee700e3b21a1260de0f2697f2a75357cacd6124e73eee39b21c0f05" }, "dob":"1977-04-27 18:44:16", "registered":"2014-12-11 11:11:29", "phone":"97377508", "cell":"04206356", "id":{ "name":"CPR", "value":"018563-3343" }, "picture":{ "large":"https://randomuser.me/api/portraits/women/58.jpg", "medium":"https://randomuser.me/api/portraits/med/women/58.jpg", "thumbnail":"https://randomuser.me/api/portraits/thumb/women/58.jpg" }, "nat":"DK" } ], "info":{ "seed":"9c5a7af03b97edcf", "results":1, "page":1, "version":"1.1" } }
用户手册:
如果您使用python来调用和处理此API,则没有问题,但是我对php不了解,只能放弃此方法。
这个想法可行,能力有限,我们将在以后进行研究
3、字典随机组合方法
方法思路: 找出外国人最普通的姓(Most Common Surnames)和最普通的名字(Most Common Male Names,多数普通的女性名字),然后将它们随机组合成一个普通的英语用户名。
function random_user() { $male_names = array("James","John","Robert","Michael","William","David","Richard","Charles","Joseph","Thomas","Christopher","Daniel","Paul","Mark","Donald","George","Kenneth","Steven","Edward"); $famale_names = array("Mary","Patricia","Linda","Barbara","Elizabeth","Jennifer","Maria","Susan","Margaret","Dorothy","Lisa","Nancy","Karen","Betty","Helen","Sandra","Donna","Carol","Ruth"); $surnames = array("Smith","Jones","Taylor","Williams","Brown","Davies","Evans","Wilson","Thomas","Roberts","Johnson","Lewis","Walker","Robinson","Wood","Thompson","White","Watson","Jackson"); $frist_num = mt_rand(0,19); $sur_num = mt_rand(0,19); $type = rand(0,1); if($type==0){ $username=$male_names[$frist_num]." ".$surnames[$sur_num]; } else { $username=$famale_names[$frist_num]." ".$surnames[$sur_num]; } return $username; }
这里使用了20个常见的男性姓名,20个常见的女性姓名和20个常见的姓氏来组合用户名。如果需要更多数据,可以在这里检查: 外国人使用的100个最常见的姓氏,在100个人中最常见。
调用方法与上述相同,生成的英文用户名如下:
玛丽·威廉姆斯,丹尼尔·约翰逊,约翰·琼斯,玛丽亚·埃文斯,唐娜·史密斯,芭芭拉·史密斯
可以看出,通过这种方法生成的英文用户名非常可靠,可读性强,并且可以生成大量数字(20 * 20 + 20 * 20共800个)。最后,我还使用了此功能。
这三种方法的思想也可以用于生成中文用户名。
Tags标签:php随机生成英文名 php随机数生成