PHP在加载的文本文件中搜索,转换为数组

时间:2015-05-04 12:50:08

标签: php

我需要在文本文档中找到*.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;
       }

2 个答案:

答案 0 :(得分:0)

下面是使用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
}

希望这有助于间接帮助。

答案 1 :(得分:0)

$string=file_get_contents($file);

file_get_contents

或者,如果您想逐行排列,只需openreadclose

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