PHP generates random string custom functions

Source: Internet
Author: User
PHP generates random string custom functions in a detailed description

/** * Generate random String * @param int       $length  The random string length to be generated * @param string    $type    random code type: 0, digit + capital letter, 1, number; 2, lowercase letter; 3, Uppercase letters, 4, special characters;-1, digits + uppercase and lowercase letters + special characters * @return string */function randcode ($length = 5, $type = 0) {    $arr = array (1 = "0123 456789 ", 2 =" ABCDEFGHIJKLMNOPQRSTUVWXYZ ", 3 =" ABCDEFGHIJKLMNOPQRSTUVWXYZ ", 4 =" ~@#$%^&* () {}[]| ");    if ($type = = 0) {        array_pop ($arr);        $string = Implode ("", $arr);    } else if ($type = = "-1") {        $string = implode ("", $arr);    } else {        $string = $arr [$type];    }    $count = strlen ($string)-1;    for ($i = 0; $i < $length; $i + +) {        $str [$i] = $string [rand (0, $count)];        $code. = $str [$i];    }    return $code;}

Let's start by talking about the function

Use Randcode () to call this function, and then pass in the parameters, $length to generate a random string length, is the number of characters, $type to generate the type of string, according to the function is written in 4 kinds of, of course, you can also add other types in, that is, The characters that are generated by each type of string are determined by the characters contained in the array.


Below is the thinkphp frame, I feel particularly strong, can recommend to everyone

/** * generates random strings that can be used to automatically generate passwords default lengths of 6-bit letters and numbers mixed with * @param string $len length * @param string $type strings type * 0 Letters 1 numbers other mixed * @param string    $addChars Extra characters * @return string */function rand_string ($len =6, $type = ', $addChars = ') {$str = ';            Switch ($type) {case 0: $chars = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz '. $addChars;        Break            Case 1: $chars = str_repeat (' 0123456789 ', 3);        Break            Case 2: $chars = ' abcdefghijklmnopqrstuvwxyz '. $addChars;        Break            Case 3: $chars = ' abcdefghijklmnopqrstuvwxyz '. $addChars;        Break Case 4: $chars = "I'm going to do it when he's going to do it. Domestic one is the Ministry of the annual Order of righteousness hair into the department of the People can go into the discord with the big this is the main human to divide the students for learn subordinate to use the same side to say that the life degree of leather and many children since the Community plus small machine also through the power line high-volume long party to the real home fixed deep method table water physical and chemical competition now Two Miyoshi 10 war non-agricultural and other anti-body road map of the new open in the knot from when two of the gifted team to make a point of fertility of their thoughts and in the inter-party due to a part of the daily profit by the pressure of the gas industry on behalf of the whole group number of fruit phase guide to the base or the moon hair, such as should be shaped like to make a heart-like dry are to turn off ask the comparison show that it is the most and outside of the five solutions to the Lin Mi Qun head meaning only Ming four Ma Wen Tong, but the bar is more public Hole leader inflow into the seat of the emotion and fly crude oil put up the problem of quality refers to the establishment of the area of the living people are very taught that the ordinary stone strong soil has root of a total of nine of the total number of the master-in-the-second re-election records seven Mountain hundred newspaper more see must be true to protect the Heat committee hand to the branch has been to repair the heath a few first avoid special type six with an indication of the return of each east of the wind back to the south-canton of the north of the drum to do the work of the joint step Class Set Number LevinUnderstanding of the axis of the single-color based on the speed of the Slavs set up in the field of weaving calendar flowers by the transmission of the fault condition of the production of fine gold boundary products to the boundary clearance to the million true study of the book Operation factory must be from the re-head of the sea-right vote children green only certificate of low-cross eight test near-injection-run cloth gate iron need to go to the county soldiers solid removal of the same as the introduction of the teeth thousand wins fine shadow Chai white lattice effect set push empty knife leaf rate of the election of the second half of the enemy beginning of the film application of the sound of the recovery of the name of red continuous drug mark is difficult to survive Probe body tight liquid send quasi-pound angle reducing dimension plate Xu broken the bottom of the field potential end sense to God will be he cun the structure of the non-friction group of the fire section of the state of the value of the United States Huang take the morning wheat cutting letter row Station sound of the attack Su Zhangmi harm hou grass ho tree fertilizer right belongs to the city of strict diameter of the left page anti-su show bitter English fast called bad move about BA material province black Wuppe Hati only needle How to plant the king eye she grabbed a pair of seedlings of the side of the source of the surrounding food injection of acid-induced samples The old but sufficient short-stroke Xuan fell the first ruler wave bearing powder to live with the test carved by enough Mitsuo to seize the branch to promote the STEM Zhou Yan Division Cuschun Super-negative sand seal change too model poverty reduction Yangyangiang analysis mu of wood say the ball toward medical school ancient rice song listen only to lose slip station another David word drum just write Liu Weilio fan for a piece of work set a friend limit surplus rewind roll create law rain let bone far help first skin broadcast gifted accounted for death poison Circle Wei Ti Xun control excited to call Cloud mutual crack grain Masterbatch Practice stopper steel top strategy double stay wrong to absorb resistance so inch shield late silk welding power Plant pro-hospital cold-bomb wrong scattered commercial visual arts out of the 0 room light blood times the lack of the pump observation of urban Chong spray soil simply no column Li Huanpan magnetic male like trapped Shong off delivery slave side run cover swing from the touch of the star Pine to win the independence of the officials of the mixed Ji-yi-qi, the broad winter chapter of the wet-biased grain to eat the valve of the mining village responsible for the hard price of a pre-vocational evaluation of the back of the damage cotton invasion of gray spear thick Luo mud The egg chest palm oxygen loving stop once dissolved camp finally outline Meng money to do the Russian shrinking sand back Chen beg the weapon carrier young which Peel forced spin the groove upside down and still ah fresh bar card coarse medium drill weak foot afraid of salt end Yin Feng Fog Crown C Street Lai Pui-spoke sausage-fu ji infiltration rui-jing squeeze seconds suspension sam rotten sugar Sheng concave tao word late silkworm billion moment Kang by the garden cavity order fragrant Meat Brother house sensitive to the production of bee urgent take the expansion of the Flying dew nuclear margin Rang Central Wu region very fast Paper night Township long scribe cylinder clip read LAN Anh Ditch b Confucianism kill vapor phosphorus difficult crystal plug flame huan Iron Supplement We bud Yongwa Dip Array Carbon show Wei tooth Bud Yong wa Oblique irrigation Eugeshun pig Yang rot please go through the crisis Sui Chu Han more green drag cattle part dyeing both autumn and winter forge Jade Summer healing Kinguizhou visit Blowing Rong Copper along the rollers to call the drought awareness stab the brain in the possession of the furnace shell sulfur coal ying casting sticking to the good fortune Reyen smoke sentence pure gradually tillage run ze slow planting Rutch The tide cross off cone Hitch defeat ship false Bright said Zhehwai cut pendulum tribute to the strength of the money instrument shen Lian ma sin ancestral car wear cargo pin Zimping draw feed Dragon Storehouse keep building song Han Xi elder brother Wash Eclipse the waste of the abdomen to the record mirror of the women's fat zhuang rub risk like the clock shake the handle of the bamboo Valley selling chaos Bridge Ober to catch up with the Wall network cross-section of the plot to hang up the lesson town in the aid of the anti-Fu Qing gather around Mo busy dance encounter rope Gu gum yanghu nail benevolence sound trace broken extension light to avoid flooding the emperor Liuha Jie Gannon the general Constitution thick island attack who Honche cannon spot to know the Spirit egg closed children release milk giant private silver Ychintan exhaustion Mold Dulle Isolated bend The pain Peak 0 Diesel Spring noon Jump Ju Shang Dingqin slightly chasing beam depletion alkali shu-gang digging blade pile-up Chest Value Qin film article in the case of seedling slow convex service shears Sichuan snow chain fishing face home of the Hubble buy Yang Zongjio race flag filter Silicon Carbon shares sit in a steaming trap gun to save the dark hole of the barrel of your song-arc explosion fallacy Tu Jin arm barrier brown land Ah Jian Zun Bean pullMo arrive thumper around seam police pick dirty ice Cambodian mouth what rice plastic send Zhao shout mat dan Watanabe planing Tiger pen dilute kun lang tea drip shallow hug point cover lun Niang ton of dip sleeve beads Female mom purple drama Tower Hammer quake old appearance jie cut the front of the suspect PA Flash PO Meng Brush The sudden disaster, Joe Tang leak smell shen melt chlorine waste stem man where rob like Pulp beside the glass also loyal sing to catch lock, especially by Uzhi pale allowable rebel livestock prisoners feel rust sweep Bilibao core Ye jian secret net jiang calcium shoulder teng withered throw rail Hall mix dad lure wish            Li Ken Wine rope Poor pond dry bubble bag long-feeding aluminum soft channel of habitual trade manure wall trend of the anti-dumping air clothing Sun Ling Ridge cheat Hugh Borrow ". $addChars;        Break Default://defaults to remove easily confusing characters Ooll and number 01, to add please use the Addchars parameter $chars = ' ABCDEFGHIJKMNPQRSTUVWXYZABCDEFGHIJKMNPQR            stuvwxyz23456789 '. $addChars;    Break    if ($len >10) {//The number of bits is too long to repeat the string $chars = $type ==1? str_repeat ($chars, $len): Str_repeat ($chars, 5);        } if ($type!=4) {$chars = Str_shuffle ($chars);    $str = substr ($chars, 0, $len); }else{//Chinese random word for ($i =0; $i < $len; $i + +) {$str. = Msubstr ($chars, Floor (Mt_rand) (0,mb_strlen ($chars,        ' Utf-8 ')-1)), 1); }} return $str;}
  • 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.