2015-05-04 14 views
0

我需要在文本文檔中找到*.jpg名稱。例如,我有一個文件夾與圖片file1,file2,file3和一個文本文件與file1,file,file3每個在一個新的行。我需要在每個*.jpg附近寫入文件中的文本,但首先我需要在文本文檔中找到相應的行。PHP搜索內部加載的文本文件,轉換爲數組

<?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; 
     } 
+0

所以,你必須與圖像文件名(1名= 1行文件? ),你想顯示它們沒有擴展名? 1.請添加一個示例,瞭解文本文件的外觀和預期輸出結果 – Rizier123

+3

問題是什麼? – maalls

+0

我得到例如picture2.jpg多種JPG,而文本文件看起來像這樣 圖片1 dimension_30x30 圖片2 dimension_40x50 圖片3 dimension_10x10(圖片名稱和尺寸在每個單獨的行)。 所以我需要找到picture2.jpg我應該在圖片附近添加什麼尺寸。並且我嘗試搜索該行,然後行+ 1是正確的答案。 – oma

回答

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 
} 

希望這有助於,間接的影響。

0
$string=file_get_contents($file); 

file_get_contents

或者,如果你想讓它一行行,只是openreadclose

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