我想在目录中的一个或多个文本文件中找到特定的文本字符串,但我不知道如何。我现在Google已经搜索了很长时间,而且我还没有找到任何东西。为此,我问你们我该如何解决这个问题?在PHP中找到多个TXT文件中的特定文本
在此先感谢。
我想在目录中的一个或多个文本文件中找到特定的文本字符串,但我不知道如何。我现在Google已经搜索了很长时间,而且我还没有找到任何东西。为此,我问你们我该如何解决这个问题?在PHP中找到多个TXT文件中的特定文本
在此先感谢。
你可以在不使用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;
}
}
}
如果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
我使用Windows :)不过我的虚拟主机使用Linux。是否有可能使这个工作在Windows上,所以我可以测试它,然后将其上传到我的虚拟主机? – Erik
您可以安装grep for Windows http://gnuwin32.sourceforge.net/packages/grep.htm(及其依赖项列在同一页上) –
如果你是在Linux中,你可以grep而不是使用PHP。对于PHP专门,你可以iterate over the files in a directory,open each as a string,find the string,并保存文件,如果字符串存在。
只需指定一个文件名,获取文件的内容,并对文件内容进行正则表达式匹配。见this和this进一步的细节就我下面的代码示例:
$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中。
谢谢!这工作像一个迷人的,但我怎么能得到一个特定的“代码”在一行?一行看起来像这样:'TME:... | UID:... | FNE:... | MSG:... | IPA:...'。 “代码”例如是“UID”。 – Erik
如果我理解正确,'if(strpos($ line,'| UID:')!== false)'可能会做你需要的。 – ghbarratt
回声应该如何处理? – Erik