我想在大型列表文件中找到一个单词。
然后,如果找到该单词,那么取出找到该单词的列表文件的整行?
到目前为止,我还没有看到任何PHP字符串函数来执行此操作
答案 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);
说明:
$result
是生成的数组。