【问题标题】:Php code that returns an array with filenames of files which contains a stringphp 代码返回一个数组,其中包含文件的文件名,其中包含一个字符串
【发布时间】:2016-07-20 03:05:56
【问题描述】:

我正在尝试制作一个什么都不接收的 Php 文件,并检查文件夹中的每个文件,在其中搜索字符串。它回显了一个包含字符串的文件名数组。有什么办法可以做到,可能内存使用率低?

非常感谢。

【问题讨论】:

  • 这个在网上很容易搜到

标签: php json


【解决方案1】:

要实现这样的目标,我建议您阅读 PHP 中的 DirectoryIterator 类、file_get_contentsstrings

这是一个示例,说明如何读取给定目录 ($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 添加尾部斜杠、跳过点文件和目录、跳过自身等)。

【讨论】:

    【解决方案2】:
    <?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);
    

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 2016-03-20
      • 1970-01-01
      • 2012-06-13
      • 2022-01-21
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多