The following methods can be used to match keywords and perform special processing on the keywords respectively. For more information, see
The code is as follows:
Header ("Content-type: text/html; charset = utf-8 ");
Function multiple_replace_words ($ word, $ replace, $ string, $ tmp_match = '# a_a #'){
Preg_match_all ('/'. $ word. '/', $ string, $ matches); // match all keywords
$ Search = explode (',', '/'. implode ('/,/', $ matches [0]). '/');
// No matching keyword exists
If (empty ($ matches [0]) return false;
// Special replacement settings
$ Count = count ($ matches [0]);
Foreach ($ replace as $ key => $ val ){
If (! Isset ($ matches [0] [$ key]) unset ($ replace [$ key]); // remove out-of-bounds replacement
}
// Merge the special replacement array and matching array
For ($ I = 0; $ I <$ count; $ I ++ ){
$ Matches [0] [$ I] = isset ($ replace [$ I])? $ Replace [$ I]: $ matches [0] [$ I];
}
$ Replace = $ matches [0];
// Prevent replacement loops, that is, the replacement character is still replaced, and a specific character $ tmp_match is temporarily replaced.
$ Replace = implode (',', $ replace );
$ Replace = str_replace ($ word, $ tmp_match, $ replace); // temporarily replace matching characters
$ Replace = explode (',', $ replace );
// Replacement
$ String = preg_replace ($ search, $ replace, $ string, 1); // replace only one of the arrays at a time
$ String = str_replace ($ tmp_match, $ word, $ string); // restores the matching character of the temporary replacement.
Return $ string;
}
// Example 1
$ String = 'aaabaaacaaadaaa ';
$ Word = 'aaa ';
$ Replace = array (null, 'XXX', 'yyy ');
Echo 'original: '. $ string .'
Output: '. multiple_replace_words ($ word, $ replace, $ string ).'
';
// Example 2
$ String = 'Chinese aaab Chinese ccaaad Chinese eee ';
$ Word = 'Chinese ';
$ Replace = array (null, '(replace Chinese 2)', '(replace Chinese 3 )');
Echo 'original: '. $ string .'
Output: '. multiple_replace_words ($ word, $ replace, $ string );
/*
Output result:
Original article: aaabaaacaaadaaa
Output: aaabxxxcyyydaaa
Original article: Chinese aaab Chinese ccaaad Chinese eee
Output: Chinese aaab (replace Chinese 2) ccaaad (replace Chinese 3) eee
//*/
Author: Zjmainstay