【问题标题】:Delete duplicate words in array with sentences in PHP用PHP中的句子删除数组中的重复单词
【发布时间】:2019-04-10 19:30:23
【问题描述】:

我有一个包含单词和句子的字符串数组。

例如:

array("dog","cat","the dog is running","some other text","some","text")

我想删除重复的单词,只留下唯一的单词。我什至想在句子中删除这些词。

结果应该是这样的:

array("dog","cat","the is running","other","some","text")

我尝试了array_unique 功能,但没有成功。

【问题讨论】:

  • 欢迎来到 SO!您对应该删除哪些重复项有什么要求?您似乎更喜欢在句子中保留单个单词,但澄清会有所帮助。
  • 如果输入数组的第一个和第三个元素被切换,输出会是什么样子?
  • 是的,我想在数组中保留唯一的单个单词。
  • 另一个跟进:" " 是您唯一的单词分隔符吗?所有内容都是按字母顺序排列还是一个空格?
  • @dWinder 谢谢老兄!!正是我想要的

标签: php arrays unique


【解决方案1】:

您可以使用 array_unique after 循环和 explode 和 array_push

$res = [];
foreach($arr as $e) {
    array_push($res, ...explode(" ", $e));
}
print_r(array_unique($res));

参考: array_pushexplodearray-unique

现场示例:3v4l

如果要保留句子,请使用:

$arr = array("dog","cat","the dog is running","some other text","some","text");

// sort first to get the shortest sentence first
usort($arr, function ($a, $b) {return count(explode(" ", $a)) - count(explode(" ", $b)); });

$words = [];
foreach($arr as &$e) {
    $res[] = trim(strtr($e, $words)); //get the word after swapping existing
    foreach(explode(" ", $e) as $w)
        $words[$w] =''; //add all new words to the swapping array with value of empty string
}

【讨论】:

    【解决方案2】:

    这个解决方案并不漂亮,但应该可以完成工作并满足手头的一些边缘情况。我假设句子字符串中的单词不超过一个空格,并且您希望保留原始顺序。

    方法是遍历数组两次,一次过滤掉重复的单个单词,然后再次过滤掉句子中的重复单词。这保证了单个单词的优先级。最后,ksort 数组(从时间复杂度的角度来看,这是丑陋的部分:到目前为止,一切都是 O(max_len_sentence * n))。

    $arr = ["dog","cat","the dog is running","some other text","some","text"];
    $seen = [];
    $result = [];
    
    foreach ($arr as $i => $e) {
        if (preg_match("/^\w+$/", $e) && 
            !array_key_exists($e, $seen)) {
            $result[$i] = $e;
            $seen[$e] = 1;
        }
    }
    
    foreach ($arr as $i => $e) {
        $words = explode(" ", $e);
    
        if (count($words) > 1) {
            $filtered = [];
    
            foreach ($words as $word) {
                if (!array_key_exists($word, $seen)) {
                    $seen[$word] = 0;
                }
    
                if (++$seen[$word] < 2) {
                    $filtered[]= $word;
                }
            } 
    
            if ($filtered) {
                $result[$i] = implode($filtered, " ");
            }
        }
    }
    
    ksort($result);
    $result = array_values($result);
    print_r($result);
    

    输出

    Array
    (
        [0] => dog
        [1] => cat
        [2] => the is running
        [3] => other
        [4] => some
        [5] => text
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      相关资源
      最近更新 更多