PHP matches multiple results in regular, randomly replacing one of the results
With regular match characters, if all substitutions are simple, using preg_replace is fine. But I'm going to have to randomly replace one of the results of the multiple matches I've got, which is a bit of a hassle. I wrote a function to solve, do not know there is no other better way. Example "I have a Dream". I have a dream. I have a dream. I have a dream. "Matching '/i/'. There are 4 matching results in the above string, so I just randomly replace one of them. I replace it with hell.
My code is as follows:
Regular handler 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]; }//Random Regular substitution function if there are multiple matched cells, randomly replace one of them. Note that global $g _rand_replace_num, $g _rand_replace_index, $g _rand_replace_str; These three global variables, and do not conflict with it//depend on a regular handler function to record the total number of matching units, Take a random value in the total range, and then treat it in the regular processing function. 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]); Total number of matched cells $g _rand_replace_num = Mt_rand (1, $find _count); A collection that conforms to the regular search criteria $g _rand_replace_index = 0; The index $g _rand_replace_str = $t _g_rand_replace_str in the actual substitution process; echo "Now found a match with {$find _count}
"; $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);
Expand thinking, I want to reduce the first result is replaced by the concept of what to do? In some cases, the first one is replaced not very well, only a small amount of the result is the first one to be replaced.