1 回答
TA贡献1817条经验 获得超14个赞
这是一个我认为可以做你想做的功能。它需要一个单词列表和一个同义词列表。处理第一个和最后一个单词,如果它们存在于同义词列表中,则替换它们(在字符串的开头或结尾,取决于同义词数组的索引)。
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
)
- 1 回答
- 0 关注
- 141 浏览
添加回答
举报