2011-11-07 85 views
7

我想在目录中的一个或多个文本文件中找到特定的文本字符串,但我不知道如何。我现在Google已经搜索了很长时间,而且我还没有找到任何东西。为此,我问你们我该如何解决这个问题?在PHP中找到多个TXT文件中的特定文本

在此先感谢。

回答

5

你可以在不使用grep的情况下得到你所需要的。当你在命令行时,Grep是一个方便的工具,但你只需要一些PHP代码即可完成你所需要的工作。

例如,这小片段,给你造成类似的grep:

$path_to_check = ''; 
$needle = 'match'; 

foreach(glob($path_to_check . '*.txt') as $filename) 
{ 
    foreach(file($filename) as $fli=>$fl) 
    { 
    if(strpos($fl, $needle)!==false) 
    { 
     echo $filename . ' on line ' . ($fli+1) . ': ' . $fl; 
    } 
    } 
} 
+0

谢谢!这工作像一个迷人的,但我怎么能得到一个特定的“代码”在一行?一行看起来像这样:'TME:... | UID:... | FNE:... | MSG:... | IPA:...'。 “代码”例如是“UID”。 – Erik

+0

如果我理解正确,'if(strpos($ line,'| UID:')!== false)'可能会做你需要的。 – ghbarratt

+0

回声应该如何处理? – Erik

10

如果Unix主机所运行,你可以在目录中进行系统调用来grep

$search_pattern = "text to find"; 
$output = array(); 
$result = exec("/path/to/grep -l " . escapeshellarg($search_pattern) . " /path/to/directory/*", $output); 

print_r($output); 
// Prints a list of filenames containing the pattern 
+0

我使用Windows :)不过我的虚拟主机使用Linux。是否有可能使这个工作在Windows上,所以我可以测试它,然后将其上传到我的虚拟主机? – Erik

+1

您可以安装grep for Windows http://gnuwin32.sourceforge.net/packages/grep.htm(及其依赖项列在同一页上) –

1

只需指定一个文件名,获取文件的内容,并对文件内容进行正则表达式匹配。见thisthis进一步的细节就我下面的代码示例:

$fileName = '/path/to/file.txt'; 
    $fileContents = file_get_contents($fileName); 
    $searchStr = 'I want to find this exact string in the file contents'; 

    if ($fileContents) { // file was retrieved successfully 

     // do the regex matching 
     $matchCount = preg_match_all($searchStr, $fileContents, $matches); 

     if ($matchCount) { // there were matches 
      // $match[0] will contain the entire string that was matched 
      // $matches[1..n] will contain the match substrings  
     } 

    } else { // file retrieval had problems 

    } 

注:这是可行的,不论你是否是在Linux中。

相关问题