在PHP中,如果我在文件中找到一个单词,我可以将该单词来自的行换成$ string

时间:2011-04-16 02:01:12

标签: php string file line strpos

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

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

到目前为止,我还没有看到任何PHP字符串函数来执行此操作

4 个答案:

答案 0 :(得分:1)

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

类似的东西:

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

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

答案 1 :(得分:1)

您可以使用preg_match:

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

$arr将包含匹配项。

答案 2 :(得分: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()可能不是很好)

答案 3 :(得分:0)

试试这个:

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

说明:

  • file()将读取您的文件并生成一系列行
  • preg_grep()将返回找到匹配模式的数组元素
  • $result是生成的数组。