【问题标题】:How to generate a random string in PHP (using 3 strings and random numbers)如何在 PHP 中生成随机字符串(使用 3 个字符串和随机数)
【发布时间】:2011-06-27 09:38:13
【问题描述】:

我有三个字符串,我想使用这三个字符串生成一个随机字符串,其中在字符串之间包含一些随机数。

谢谢

Ex: first string : john
    second string : smith
    third string : john9k

    I want a random string like : john.simth190, smith.john9k, john9k.123.smith, etc.,

如何在 PHP 中做到这一点。

谢谢

【问题讨论】:

  • rand() 会给你随机数和点 (.) 执行字符串连接,例如echo 'john' . rand(1, 1000) . '.smith'; 可能会产生 john271.smith。

标签: php string random


【解决方案1】:

你可以试试这样的:

<?php 
function random($items, $min=0, $max=100, $random_parts=2, $delimiter="."){
    #make sure items is an array
    $items = (array)$items;        

    #add as many random bits as required.
    for($x=0; $x<$random_parts; $x++)
          $items[] = rand($min, $max);

    #shuffle and join them
    shuffle($items);
    return implode($delimiter, $items);
}

基本上它的作用是接受一个名称数组,array('john','smith','john9k')。然后它采用 min rand 和 max rand 参数。最后它接受你想要的随机数的数量。

所以我会这样称呼它:

<?php
echo random(array('john','smith','john9k'), 0, 100, rand(0,10));

【讨论】:

  • 这很好,但我认为在这种情况下它是一个随机字节,而不是一个随机位。
  • 抱歉,我的意思是它是随机部分,而不是位或字节。想不出这个词,但谢谢你提到它,我已经更新了它
  • @Jason:非常好的逻辑和实现。谢谢。但是我在 implode 函数处收到错误警告:implode() [function.implode]: Invalid arguments pass in
  • @Jason:我明白了。我们必须在 implode 函数之外对数组进行洗牌。洗牌($项目);然后 implode($delimiter, $items);
  • 哦,是的,shuffle 返回一个布尔值,而不是修改后的数组。
【解决方案2】:

你也可以试试

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]].$input[$rand_keys[1]].rand(0,100);

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 2011-05-20
    • 1970-01-01
    • 2017-08-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多