I need to find a *.jpg
name in a text document. For example I have a folder with pictures file1
, file2
, file3
and a text document with file1
, file
, file3
each on a new line. I need to write near each *.jpg
the text from the file, but first I need to find the corresponding row in the text document.
<?php
$arrayF = explode("
", 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;
}
Below is an example to iterate through a directory using DirectoryIterator which provides viewing contents of filesystem directories.
Example:
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"
}
To elaborate new DirectoryIterator( path to dir )
provides an iterator which can be also written as:
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
// do stuffs
}
Hope this helps, indirectly.