【发布时间】:2016-07-20 03:05:56
【问题描述】:
我正在尝试制作一个什么都不接收的 Php 文件,并检查文件夹中的每个文件,在其中搜索字符串。它回显了一个包含字符串的文件名数组。有什么办法可以做到,可能内存使用率低?
非常感谢。
【问题讨论】:
-
这个在网上很容易搜到
我正在尝试制作一个什么都不接收的 Php 文件,并检查文件夹中的每个文件,在其中搜索字符串。它回显了一个包含字符串的文件名数组。有什么办法可以做到,可能内存使用率低?
非常感谢。
【问题讨论】:
要实现这样的目标,我建议您阅读 PHP 中的 DirectoryIterator 类、file_get_contents 和 strings。
这是一个示例,说明如何读取给定目录 ($dir) 的内容并使用 strstr 在每个文件的内容 ($contents) 中搜索特定字符串:
<?php
$dir = '.';
if (substr($dir, -1) !== '/') {
$dir .= '/';
}
$matchedFiles = [];
$dirIterator = new \DirectoryIterator($dir);
foreach ($dirIterator as $item) {
if ($item->isDot() || $item->isDir()) {
continue;
}
$file = realpath($dir . $item->getFilename());
// Skip this PHP file.
if ($file === __FILE__) {
continue;
}
$contents = file_get_contents($file);
// Seach $contents for what you're looking for.
if (strstr($contents, 'this is what I am looking for')) {
echo 'Found something in ' . $file . PHP_EOL;
$matchedFiles[] = $file;
}
}
var_dump($matchedFiles);
我鼓励您阅读和了解此示例中的一些额外代码(向 $dir 添加尾部斜杠、跳过点文件和目录、跳过自身等)。
【讨论】:
<?php
$folderPath = '/htdocs/stock/tae';
$searchString = 'php';
$cmd = "grep -r '$searchString' $folderPath";
$output = array();
$files = array();
$res = exec($cmd, $output);
foreach ($output as $line) {
$files[] = substr($line, 0, strpos($line, ':'));
}
print_r($files);
【讨论】: