【问题标题】:PHP search inside loaded text file, converted as arrayPHP在加载的文本文件中搜索,转换为数组
【发布时间】:2015-05-04 12:50:07
【问题描述】:

我需要在文本文档中找到*.jpg 名称。例如,我有一个带有图片file1file2file3 的文件夹和一个带有file1filefile3 的文本文档,每个都在一个新行上。我需要在每个*.jpg附近写下文件中的文本,但首先我需要在文本文档中找到对应的行。

 <?php
 $arrayF = explode("\n", file_get_contents('myTxt.txt'));
 // arrayF should the the array with each text line from the txt file.
  while(($file = readdir($opendir)) !== FALSE)
       {
           if($file!="." && $file!="..")
           {
                $string=$file;
                $arrayS = explode('.', $string);//get the name only without .jpg extension
                $search=$arrayS[0];

        $key = array_search($search, $arrayF);

        echo $key;
       }

【问题讨论】:

  • 所以您有一个带有图像文件名的文件(1 个名称 = 1 行?!)并且您想在没有扩展名的情况下显示它们? 1. 请添加一个示例文本文件的外观以及您的预期输出是什么
  • 问题是什么?
  • 我有多个 jpg 例如picture2.jpg,文本文件看起来像这样 picture1 dimension_30x30 picture2 dimension_40x50 picture3 dimension_10x10 (图片名称和尺寸分别在不同的行中)。所以我需要为picture2.jpg找到我应该在图片附近添加什么尺寸。我尝试搜索行然后行+1是正确的答案。
  • 我的意思是我试图在 txt 文件中找到图片 2.jpg 的名称......我喜欢这条线,我可以得到作为维度的 line+1..但是 array_search 函数不起作用我..

标签: php


【解决方案1】:
$string=file_get_contents($file);

file_get_contents

或者,如果您希望逐行显示,只需 openreadclose

$fp = fopen($file, 'r');
while ($line = fread($fp)) {
//do comparision stuff
}
fclose ($fp);

【讨论】:

    【解决方案2】:

    下面是一个使用DirectoryIterator 遍历目录的示例,它提供了文件系统目录的查看内容。

    例子:

    foreach(new DirectoryIterator($dir) as $file_info)
    {
        // sleep a micro bit (up to 1/8th second)
        usleep(rand(0, 125000));
    
        // disregard hidden, empty, invalid name files
        if($file_info == null or $file_info->getPathname() == '' 
                              or $file_info->isDot())
        {
            continue;
        }
    
        // check if its a file - log otherwise
        // code omitted
    
        // get filename and filepath
        $filepath = $file_info->getPathname();
        $filename = $file_info->getFilename();
    
       // my answer to read file linked here to avoid duplication
       // below "read/parse file into key value pairs"
    }
    

    read/parse file into key value pairs

    详细说明new DirectoryIterator( path to dir )提供了一个迭代器,也可以写成:

    $iterator = new DirectoryIterator($directory);
    foreach ($iterator as $fileinfo) {
      // do stuffs
    }
    

    希望这间接地有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多