Random string generation class

Source: Internet
Author: User
Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn to generate random strings based on the format and rules specified by the user. It supports multi-layer nesting and constant conversion. The attachment contains the instance and default rule files.


RandEx. php Namespace RandEx;
Include "Functions. php ";
Class RandEx {
// Constructor. format is the format for generating random strings. rule is the custom generation rule and const is the custom constant.
Public function _ construct ($ format = null, $ rules = null, $ const = ""){
$ This-> format = is_null ($ format )? "": $ Format;
If (is_null ($ rules ))
// If no custom rule is specified, read the RulesDefault. ini in the directory as the rule
$ Rules = file_get_contents (_ DIR _. "/RulesDefault. ini ");
$ This-> config ($ rules, $ const );
}
// Set the format ($ type = 0), Rule (1), constant (2)
Public function set ($ str = null, $ type ){
Switch ($ type ){
Case 0:
$ This-> format = is_null ($ str )? "": $ Str;
Break;
Case 1:
If (is_null ($ str ))
$ Str = file_get_contents ("RulesDefault. ini ");
$ This-> config ($ str );
Break;
Case 2:
$ This-> config (null, $ str );
Break;
}
}
// Generate a random string based on the configured rules. The number is the number (1 by default ). If the value is not 1, a two-dimensional array is returned.
Public function generate ($ number = 1 ){
If ($ number <1)
Return $ this-> format;
For ($ I = 0; $ I <$ number; $ I ++ ){
$ Str = $ this-> format;
// Make a judgment after each string replacement. If the string content is not changed, the loop ends.
Do {
$ TempStr = $ str;
$ Str = $ this-> formatConvert ($ str );
$ Str = $ this-> constConvert ($ str );
} While ($ tempStr! ==$ Str );
If ($ number = 1)
Return $ str;
$ Ret [] = $ str;
}
Return $ ret;
}
// Destructor
Public function _ destruct (){}
// Parsing rules, which are saved in private member variables in the form of multi-dimensional arrays
Private function config ($ rules = null, $ const = null ){
// Use line breaks to separate
If (! Is_null ($ rules )){
Unset ($ this-> rules );
$ RulesArr = explode ("\ r \ n", $ rules );
$ ArrCount = count ($ rulesArr );
If ($ arrCount = 0)
$ This-> rules = array (), array ()));
For ($ I = 0; $ I <$ arrCount; $ I ++ ){
$ TempArr = explode (":", $ rulesArr [$ I], 2 );
If (count ($ tempArr )! = 2)
Continue;
$ This-> rules [0] [] = $ tempArr [0];
$ This-> rules [1] [] = explode (",", $ tempArr [1]);
}
}
If (! Is_null ($ const )){
Unset ($ this-> const );
$ ConstArr = explode ("\ r \ n", $ const );
$ ArrCount = count ($ constArr );
If ($ arrCount = 0)
$ This-> const = array (), array ());
For ($ I = 0; $ I <$ arrCount; $ I ++ ){
$ TempArr = explode (":", $ constArr [$ I], 2 );
If (count ($ tempArr )! = 2)
Continue;
$ This-> const [0] [] = $ tempArr [0];
$ This-> const [1] [] = $ tempArr [1];
}
}
}
// Use the specified rule to convert strings
Private function formatConvert ($ str ){
$ C = count ($ this-> rules [0]);
$ Str = self: innerConvert ($ str );
For ($ I = 0; $ I <$ c; $ I ++ ){
$ Find = "[*". $ this-> rules [0] [$ I]. ":";
While (strpos ($ str, $ find )! = False ){
$ ReplaceCount = count ($ this-> rules [1] [$ I]);
$ RangeStr = strBetween ($ str, $ find, "*]");
$ RangeArr = explode (",", $ rangeStr, 2 );
If (count ($ rangeArr )! = 2)
Break;
Mt_srand ();
// Number of times generated
$ Loop = mt_rand ($ rangeArr [0], $ rangeArr [1]);
$ TempStr = "";
For ($ j = 0; $ j <$ loop; $ j ++)
$ TempStr. = $ this-> rules [1] [$ I] [mt_rand (0, $ replaceCount-1)];
$ Str = str_replace_once ($ find. $ rangeStr. "*]", $ tempStr, $ str );
}
}
Return $ str;
}
// Conversion constant
Private function constConvert ($ str ){
// Convert to comma
$ Str = str_replace ("{* C *}", $ str );
// Convert it to a line break, which can be changed to \ n, \ r, \ r \ n as needed
$ Str = str_replace ("{* B *}","
", $ Str );
$ C = count ($ this-> const [0]);
For ($ I = 0; $ I <$ c; $ I ++ ){
$ Find = "{*". $ this-> const [0] [$ I]. "*}";
$ Str = str_replace ($ find, $ this-> const [1] [$ I], $ str );
}
Return $ str;
}
// Use built-in rules for String Conversion
Private static function innerConvert ($ str ){
Mt_srand ();
// Random English letters
While (strpos ($ str, "[* :")! = False ){
$ Result = strBetween ($ str, "[* A:", "*]");
$ Arr = explode (",", $ result, 3 );
If (count ($ arr) <2)
Break;
If (count ($ arr) = 2)
$ Arr [] = "0 ";
$ Replace = randAlphabet (mt_rand (int) $ arr [0], (int) $ arr [1]), (int) $ arr [2]);
$ Str = str_replace_once ("[* A:". $ result. "*]", $ replace, $ str );
}
// Random Chinese characters, numbers, letters + numbers
For ($ I = 0; $ I <4; $ I ++ ){
$ Prefix = array ("[* C:", "[* N:", "[* S:", "[* I :");
While (strpos ($ str, $ prefix [$ I])! = False ){
$ Result = strBetween ($ str, $ prefix [$ I], "*]");
$ Arr = explode (",", $ result, 2 );
If (count ($ arr )! = 2)
Break;
If ($ I = 3)
$ Replace = randInteger (int) $ arr [0], (int) $ arr [1]);
Else
$ Replace = randAll ($ I, mt_rand (int) $ arr [0], (int) $ arr [1]);
$ Str = str_replace_once ($ prefix [$ I]. $ result. "*]", $ replace, $ str );
}
}
// Obtain the system time
While (strpos ($ str, "[* D :")! = False ){
$ Result = strBetween ($ str, "[* D:", "*]");
$ Replace = date ($ result );
$ Str = str_replace ("[* D:". $ result. "*]", $ replace, $ str );
}
Return $ str;
}
Private $ format;
Private $ rules;
Private $ const;
}
Functions. php // Extract the strings in the middle of two substrings from a string
Function strBetween ($ str, $ left, $ right ){
$ LeftPos = strpos ($ str, $ left );
$ LeftLen = strlen ($ left );
$ RightPos = strpos ($ str, $ right, $ leftPos + $ leftLen );
If ($ leftPos = false | $ rightPos = false)
Return "";
Return substr ($ str, $ leftPos + $ leftLen, $ rightPos-$ leftPos-$ leftLen );
}
// Replace the str_replace version only once
Function str_replace_once ($ search, $ replace, $ subject ){
$ Pos = strpos ($ subject, $ search );
If ($ pos = false)
Return $ subject;
Return substr_replace ($ subject, $ replace, $ pos, strlen ($ search ));
}
// Generate a specified number of random Chinese characters and return a string
Function randChinese ($ number ){
Mt_srand ();
$ RandStr = "";
For (; $ number> 0; $ number --)
// Random GBK Chinese
$ RandStr. = chr (mt_rand (176,218). chr (mt_rand (176,218 ));
// Convert to UTF-8
$ RandStr = iconv ("GB2312", "UTF-8", $ randStr );
Return $ randStr;
}
// Generate a specified number of random numbers and return a string
Function randNumber ($ number ){
Mt_srand ();
$ RandStr = "";
For (; $ number> 0; $ number --)
$ RandStr. = chr (mt_rand (48, 57 ));
Return $ randStr;
}
// Generate an integer in the specified range
Function randInteger ($ min, $ max ){
Return (string) mt_rand ($ min, $ max );
}
// Generate a specified number of random English letters. If type is 0, it is case-insensitive. If type is 1, it is case-insensitive and case-insensitive. Returns a string.
Function randAlphabet ($ number, $ type ){
Mt_srand ();
$ RandStr = "";
Loop: if ($ number = 0)
Return $ randStr;
If ($ type = 0 ){
// Random case sensitivity
If (mt_rand (0, 1) = 0)
Goto lower;
Goto upper;
}
// Uppercase letters
If ($ type = 1 ){
Upper: $ randStr. = chr (mt_rand (65, 90 ));
Goto sub;
}
// Lowercase letters
If ($ type = 2 ){
Lower: $ randStr. = chr (mt_rand (97,122 ));
} Else {
Return "";
}
Sub: $ number --;
Goto loop;
}
// Generate a specified number of random characters, including numbers and uppercase/lowercase letters. Returns a string.
Function randChar ($ number ){
Mt_srand ();
$ RandStr = "";
For (; $ number> 0; $ number --){
$ Case = mt_rand (0, 2 );
If ($ case = 0)
Goto upper;
If ($ case = 1)
Goto lower;
Num: $ randStr. = chr (mt_rand (48, 57 ));
Continue;
Upper: $ randStr. = chr (mt_rand (65, 90 ));
Continue;
Lower: $ randStr. = chr (mt_rand (97,122 ));
}
Return $ randStr;
}
Function randAll ($ type, $ arg ){
If ($ type = 0)
Return randChinese ($ arg );
If ($ type = 1)
Return randNumber ($ arg );

Return randChar ($ arg );
}

RandEx.zip (11.04 KB download: 5 times)

AD: truly free, domain name + VM + enterprise mailbox = 0 RMB

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.