Php simple random string generation method example, php string example

Source: Internet
Author: User

Php simple random string generation method example, php string example

This example describes how to generate a simple random string in php. We will share this with you for your reference. The details are as follows:

<?phpfunction rand_str($length,$p='all'){ $nums = '0123456789'; $lowers = 'abcdefghijklmnopqrstuvwxyz'; $uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; if ($p == 'all') {  $src = $nums.$lowers.$uppers; } else {  $src = '';  if (strpos($p, 'num') !== false)   $src .= $nums;  if (strpos($p, 'lower') !== false)   $src .= $lowers;  if (strpos($p, 'upper') !== false)   $src .= $uppers; } return $src? substr(str_shuffle($src), 0, $length) : $src;}?>

I searched the php functions of random strings on the Internet and found that most implementations use loops. This is a little inefficient. in php, there are all kinds of functions that you can't think. the str_shuffle () function can easily implement random strings. however, we recommend you encapsulate it. After all, some people only need to use uppercase letters and only numbers.

The second parameter num, lower, and upper of the function can be combined at will.

The true core statement is only one line

substr(str_shuffle($src), 0, $length)

The function is to unsequence the string $ src and intercept the first $ length characters.

PS: here we will provide you with an online tool with similar functions for your reference:

Online random number/string generation tool:
Http://tools.jb51.net/aideddesign/suijishu

High-strength Password generator:
Http://tools.jb51.net/password/CreateStrongPassword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.