我正在尝试使用这些字符串之间最常见的单词从多个字符串创建一个新字符串。例如:
$string[0] = 'Apple iPhone 4S 16GB Locked to Orange';
$string[1] = 'iPhone 4S 16GB boxed new';
$string[2] = 'iPhone 4S 16GB unlocked brand new';
$string[3] = 'Apple iPhone 16GB 4S Special Offer';
$string[4] = 'Apple iPhone 4S Sim Free';
## The new string should be:
$new_string = 'Apple iPhone 4S 16GB';
可能有数百个原始字符串,或者只有 2 个...
我不知道从哪里开始,任何帮助将不胜感激。
最佳答案
你可以试试
$string = array();
$string[0] = 'Apple iPhone 4S 16GB Locked to Orange';
$string[1] = 'iPhone 4S 16GB boxed new';
$string[2] = 'iPhone 4S 16GB unlocked brand new';
$string[3] = 'Apple iPhone 16GB 4S Special Offer';
$string[4] = 'Apple iPhone 4S Sim Free';
print(getCommon($string));
输出
Apple iPhone 4S 16GB
使用的函数
function getCommon($array,$occurance = 3)
{
$array = array_reduce($array, function($a,$b) { $a = array_merge($a,explode(" ", $b)); return $a; },array());
return implode(" ",array_keys(array_filter(array_count_values($array),function($var)use($occurance) {return $var > $occurance ;})));
}
关于php - 来自具有最常见单词的多个字符串的新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876272/