Home  >  Article  >  Backend Development  >  How to get any four strings in php

How to get any four strings in php

angryTom
angryTomOriginal
2019-11-01 11:16:383446browse

How to get any four strings in php

How to get any four strings in php

1. First, we write a getRandomStr function, Pass in two parameters, the first parameter is the length of the generated string, and the second parameter is whether special characters are required.

<?php
/**
 * 获得随机字符串
 * @param $len             需要的长度
 * @param $special        是否需要特殊符号
 * @return string       返回随机字符串
 */
function getRandomStr($len, $special=true){
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    if($special){
        $chars = array_merge($chars, array(
            "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
            "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
            "}", "<", ">", "~", "+", "=", ",", "."
        ));
    }
    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = &#39;&#39;;
    for($i=0; $i<$len; $i++){
        $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
}

2. Then we call the getRandomStr function 4 times and print it.

echo getRandomStr(8, false) , &#39;<br>&#39;;
echo getRandomStr(8, false) , &#39;<br>&#39;;
echo getRandomStr(8, false) , &#39;<br>&#39;;
echo getRandomStr(8, false) , &#39;<br>&#39;;

Effect: (Here I generated 4 8-bit strings, excluding special characters)

GRbgpepX
4thOLZln
hkBoGY1Q
G9DROwtd

3. We can also save it through an array Results generated 4 times.

$arr = array(
    getRandomStr(8, false),
    getRandomStr(8, false),
    getRandomStr(8, false),
    getRandomStr(8, false)
);
var_dump($arr);

Result:

array(4) { [0]=> string(8) "J02AzMyt" [1]=> string(8) "CN4W715t" [2]=> string(8) "ApSfn7rB" [3]=> string(8) "4yn5ivHz" }

And use the subscript to make a separate call:

echo $arr[0];

Result:

J02AzMyt

More For more PHP related knowledge, please visit PHP中文网!

The above is the detailed content of How to get any four strings in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn