簡體   English   中英

使用regex php匹配文件中的單詞

[英]Match words in file with regex php

我是regex和php的新手。 我知道這很簡單,但我無法理解。 現在,我有包含以下內容的words.txt文件:

happy
sad
laugh

我想找到與我的words.txt匹配的這句話:

我很開心

到目前為止,我已經嘗試過了,但是它無效,因為它讀為句子而不是單詞:(尚未實現regex bcs im混淆)

$input0= "I am happy";
$handle = fopen('words.txt', 'r');
$valid = false; 
while (($buffer = fgets($handle)) !== false) {
if (strpos($buffer, $input0) !== false) { // here's the problem
    $valid = TRUE;
    break;
   }      
}
if($valid == TRUE){
//print the matches word
}
fclose($handle);

你能幫我嗎? :(

根據您的最終目標,您可能甚至不需要在這里使用正則表達式,因為您希望匹配不帶可變部分的整個單詞。

如果您想在關鍵字上循環,那么一個簡單的str_replace()便可以用一個強調單詞替換該單詞,或者簡單地通過if (strpos($input0, $word) !== false)來檢查該if (strpos($input0, $word) !== false)如果在句子中找到位置。

但是,如果您想避免循環,則可以更快地獲得結果 ,尤其是當您有很多單詞時,如Zanderwar所說, preg_match_all()可以滿足您的需求。 這是一個例子:

$input0= "I am happy but sometimes quite pretty sad. It depends but I prefer to be happy in general.\nMy paragraph also continue on multilines\nend it makes me laugh and rejoy. I am so happy. HAPPY?";
// $contents = file_get_contents('words.txt');
$contents = "happy\nsad\nlaugh";

$words_list = str_replace("\n", '|', $contents);

if (preg_match_all("~($words_list)~si", $input0, $matches))
{
    print_r(array($matches));
    // Do what you want
}

如果需要, i標志不區分大小寫。

s標志在多行內容上匹配。

[EDIT]添加有關regexp的更多詳細信息

在模式中,您需要一個定界符,該定界符可以是~因為很少在句子和字符串中使用它來匹配,因此您無需像使用/分隔符那樣轉義/

如果您想捕獲單詞,我也會加入您的單詞,例如~(sad|joy|happy)~ 如果您不這樣做,則需要一個類似(?:sad|joy|happy)的團體

| 意味着或。

如果不需要捕獲,則可以嘗試用~(?:$words_list)~si ~($words_list)~si替換正則表達式~($words_list)~si ~(?:$words_list)~si然后,您將在$ matches數組中只有一層捕獲,即位置[0]始終是完整匹配。 但是這里您沒有更復雜的模式可以匹配,因此無需捕獲

暫無
暫無

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

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