1

我想在一个大列表文件中找到一个单词。

然后,如果找到该单词,则取出该单词所在的列表文件的整行?

到目前为止,我还没有看到任何 PHP 字符串函数可以做到这一点

4

4 回答 4

1
$path = "/path/to/wordlist.txt";
$word = "Word";

$handle = fopen($path,'r');
$currentline = 1;  //in case you want to know which line you got it from
while(!feof($handle))
{
    $line = fgets($handle);
    if(strpos($line,$word))
    {
        $lines[$currentline] = $line;
    }
    $currentline++;
}
fclose($handle);

如果您只想找到单词出现的单行,那么不要将其保存到数组中,而是将其保存在某个地方,并break在匹配后进行。

这应该可以在任何大小的文件上快速工作(在大文件上使用 file() 可能不好)

于 2011-04-16T02:30:41.193 回答
1

使用行分隔的正则表达式查找单词,然后您的匹配将包含整行。

就像是:

preg_match('^.*WORD.*$, $filecontents, $matches);

然后$matches将有它找到的地方的完整行WORD

于 2011-04-16T02:05:44.473 回答
1

您可以使用 preg_match:

$arr = array();
preg_match("/^.*yourSearch.*$/", $fileContents, $arr);

$arr然后将包含匹配项。

于 2011-04-16T02:06:55.553 回答
0

试试这个:

$searhString = "search";
$result = preg_grep("/^.*{$searhString}.*$/", file('/path/to/your/file.txt'));
print_r($result);

解释:

  • file()将读取您的文件并生成行数组
  • preg_grep()将返回找到匹配模式的数组元素
  • $result是结果数组。
于 2011-04-16T02:15:09.753 回答