簡體   English   中英

使用正則表達式和PHP從字符串中查找第一個匹配項?

[英]Finding the first occurrence from a string using regex and PHP?

我正在嘗試從正文中找到所有唯一的完整單詞。 目前,這是我正在使用的,但似乎無法正常工作:

$textDump = "cat dog monkey cat snake horse"
$wholeWord = "/[\w]*/";
$uniqueWords = (preg_match($wholeWord, $textDump, $matches));

任何幫助,將不勝感激。 謝謝!

array_unique(
    str_word_count($textDump,1)
);

您可以使用str_word_count

$textDump = "cat dog monkey cat snake horse";
$uniqueWords = (str_word_count($textDump, 1);

為什么不使用explode();實現此目的explode(); array_unique(); 在這種情況下?

$text = "cat dog monkey cat snake horse";

$foo = explode(" ", $text);
print_r(array_unique($foo)); 

到目前為止給出的答案都假定,“找到所有唯一的完整單詞”實際上意味着“刪除重復項”。 實際上,您的問題還不是很清楚,因為您沒有在示例中指定所需的輸出,但是我會按您的意願為您提供“找到所有唯一的完整單詞”的解決方案。

對於輸入,這意味着:

"cat dog monkey cat snake horse"

您將獲得輸出:

"dog monkey snake horse"

實際上, str_word_count都可以用於此array_count_values ,后者實際上可以計算不同的

$wordCount = array_count_values(str_word_count($textDump,1));

$wordCount現在是:

array(5) {
  ["cat"]    => int(2)
  ["dog"]    => int(1)
  ["monkey"] => int(1)
  ["snake"]  => int(1)
  ["horse"]  => int(1)
}

接下來,刪除單詞數大於1的單詞(請注意,實際單詞是數組鍵,因此我們使用array_keys來獲取它們:

$uniqueWords = array_keys(
    array_filter(
        $wordCount,
        function($count) {
            return $count === 1;
        }
    )
);

$uniqueWords現在是:

array(4) {
  [0] => string(3) "dog"
  [1] => string(6) "monkey"
  [2] => string(5) "snake"
  [3] => string(5) "horse"
}

完整的代碼:

$textDump = "cat dog monkey cat snake horse";
$wordCount = array_count_values(str_word_count($textDump,1));
$uniqueWords = array_keys(
    array_filter(
        $wordCount,
        function($count) {
            return $count === 1;
        }
    )
);
echo join(' ', $uniqueWords);
//dog monkey snake horse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM