In php, multiple results are matched with regular expressions, and one result is randomly replaced with regular expression matching characters. if it is easy to replace all, use preg_replace. But now I want to randomly replace one of the multiple matched results, which is a little troublesome. I wrote a function to solve the problem. I don't know if there are any other better methods. In the example, "Ih php matches multiple results with regular expressions and replaces one result randomly.
Use regular expressions to match characters. if you replace all the characters, you can use preg_replace. But now I want to randomly replace one of the multiple matched results, which is a little troublesome. I wrote a function to solve the problem. I don't know if there are any other better methods. Example: "I have a dream. I have a dream." matches '/I /'. The above string contains four matching results. I only need to randomly replace one of them. Replace I with hell.
My code is as follows:
// Function rand_replace_callback ($ matches) {global $ g_rand_replace_num, $ g_rand_replace_index, $ region; $ g_rand_replace_index ++; if ($ region = $ g_rand_replace_index) {return $ g_rand_replace_str;} else {return $ matches [0] ;}// if there are multiple matching units, replace one of them randomly. // Note that global $ g_rand_replace_num, $ g_rand_replace_index, $ g_rand_replace_str; do not conflict with other global variables. // The total number of matching units in the record of a regular expression processing function, take a random value in the range of the total number and process it if the regular expression processing function is equal. Function rand_preg_replace ($ pattern, $ rule, $ string) {global $ g_rand_replace_num, $ g_rand_replace_index, $ g_rand_replace_str; preg_match_all ($ pattern, $ string, $ out ); $ find_count = count ($ out [0]); // The total number of matched units $ g_rand_replace_num = mt_rand (1, $ find_count ); // Set $ g_rand_replace_index = 0 that meets regular expression search criteria; // index $ g_rand_replace_str = $ t_g_rand_replace_str; echo "{$ find_count} are found
"; $ Ss = preg_replace_callback ($ pattern," rand_replace_callback ", $ string); return $ ss ;}$ string =" I have a dream. I have a dream. I have a dream. I have a dream. "; echo rand_preg_replace ('/I/'," hell ", $ string );
What should I do if I want to reduce the concept of replacing the first result? In some cases, the first replacement is not very good, but a small number of results are required to replace the first one.