Home > Article > Backend Development > PHP String Exercise 1: Generate Random Password from Given String
Welcome everyone to my channel! Today I started playing a new series, which is about how to play PHP strings. Don’t miss it if you pass by. Everyone is also welcome to give reasonable suggestions. I am not a big boss, I am just dedicated to getting new people started, but the technology is big For my senior explanation, you can watch "PHP Video Tutorial", everything you want is here!
So, let’s start the text!
As the title states, the center of this article is about the implementation of generating random passwords. So when implementing random numbers in PHP, everyone’s first reaction is probably the rand
function, but today we are not allowed to use rand! (For the use of rand, you can read "PHP Mathematical Function Practice 3: Clever Use of Random Function rand()")
Without rand(), there are naturally other methods. I will give it below. Let's introduce another simple method to implement random numbers:
Directly code:
<?php function password_generate($chars) { $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; return substr(str_shuffle($data), 0, $chars); } echo password_generate(7)."\n";
First define a password_generate method, then define a string in the method body, and then combine str_shuffle and substrh function to generate.
The string we are given here is "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz", and the requirement is to have a random password in this string.
The running results are as follows:
It’s still very simple!
Here, we use two important functions, the str_shuffle()
and substr()
functions.
str_shuffle()
The function is used to randomly shuffle all characters in a string, and its syntax is "str_shuffle(string)
". The return value is a scrambled string.
substr()
The function is used to return a part of the string. Its syntax is "substr(string,start,length)
" and the return value is the return string. The extraction part, if it fails, returns FALSE, or returns an empty string.
It should be noted that if the start parameter is a negative number and length is less than or equal to start, then length is 0.
Finally, I would like to recommend a classic course on our platform "PHP String Processing (Jade Girl Heart Sutra Edition)". It's free~ Come and learn!
The above is the detailed content of PHP String Exercise 1: Generate Random Password from Given String. For more information, please follow other related articles on the PHP Chinese website!