Match multiple results with regular expressions in php and replace one result randomly. Use regular expressions to match characters. if you replace all the characters, you can use preg_replace. However, I want to randomly replace one of the multiple matched results, which uses 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. 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:
[Php]
// Regular expression processing function
Function rand_replace_callback ($ matches ){
Global $ g_rand_replace_num, $ g_rand_replace_index, $ g_rand_replace_str;
$ G_rand_replace_index ++;
If ($ g_rand_replace_num = $ g_rand_replace_index ){
Return $ g_rand_replace_str;
} Else {
Return $ matches [0];
}
}
// If the random regular expression replacement function has multiple matching units, replace one of them randomly.
// Note global $ g_rand_replace_num, $ g_rand_replace_index, $ g_rand_replace_str; do not conflict with other global variables.
// A regular expression processing function is used to record the total number of matching units, take a random value within the range of the total number, and process the result when the regular expression processing function determines that the number is equal.
Function rand_preg_replace ($ pattern, $ t_g_rand_replace_str, $ 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); // A set that meets regular search criteria
$ G_rand_replace_index = 0; // index during actual replacement
$ G_rand_replace_str = $ t_g_rand_replace_str;
Echo "now {$ find_count} matching items are found
";
$ Ss = preg_replace_callback ($ pattern, "rand_replace_callback", $ string );
Return $ ss; www.2cto.com
}
$ String = "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.
Bytes. However, I want to randomly replace one of the multiple matched results...