大话西游666
这是一个我认为可以做你想做的功能。它需要一个单词列表和一个同义词列表。处理第一个和最后一个单词,如果它们存在于同义词列表中,则替换它们(在字符串的开头或结尾,取决于同义词数组的索引)。function swap_words($words, $synonyms) { $all_synonyms = array_unique(array_merge(...$synonyms)); $result = []; $word = $words[0]; if (in_array($word, $all_synonyms)) { foreach ($synonyms[1] as $replacement) { $result[] = "$replacement " . implode(' ', array_slice($words, 1)); } foreach ($synonyms[2] as $replacement) { $result[] = implode(' ', array_slice($words, 1)) . " $replacement"; } } $c = count($words) - 1; $word = $words[$c]; if (in_array($word, $all_synonyms)) { foreach ($synonyms[1] as $replacement) { $result[] = "$replacement " . implode(' ', array_slice($words, 0, $c)); } foreach ($synonyms[2] as $replacement) { $result[] = implode(' ', array_slice($words, 0, $c)) . " $replacement"; } } return $result;}用法:$words = ['no of', 'autumn', 'sales'];$tot = ['1'=>array('count','total','num of','no of', 'no. of'), '2'=>array('count')];print_r(swap_words($words, $tot));$words = ['autumn', 'sales', 'count'];print_r(swap_words($words, $tot));在这两种情况下,输出都是Array ( [0] => count autumn sales [1] => total autumn sales [2] => num of autumn sales [3] => no of autumn sales [4] => no. of autumn sales [5] => autumn sales count)