<?php // demo/temp_jasmine.php
/**
* https://www.experts-exchange.com/questions/28966264/My-output-has-a-on-the-name-and-the-file-doesn't-open-anymore.html
*
For example; My file is 4867586.5010.476564.ed
After the code executes and reads the file, the output should be: 4867586_SMIL01_476564.ed but instead its: 4867586_SMIL01
And when I checked it out on putty the file name was: 4867586_SMIL01?_476564.ed
*/
error_reporting(E_ALL);
//expression to be found in file name
$find = '.5010.';
//directory name
//we will store renamed files here
$dirname = '5010';
if(!is_dir($dirname)) mkdir($dirname, 0777);
//read all files from a directory
//skip directories
$directory_with_files = './';
$directory_with_files = 'storage'; // USE THIS DIRECTORY FOR TESTS
$dh = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
if(in_array($filename, array('.', '..')) || is_dir($filename))
continue;
$files[] = $filename;
}
//iterate collected files
foreach($files as $file)
{
//check if file name is matching $find
if(stripos($file, $find) !== false)
{
$handle = fopen($directory_with_files . DIRECTORY_SEPARATOR . $file, "r");
if ($handle)
{
while (($line = fgets($handle)) !== false)
{
$line = trim($line); // REMOVE UNWANTED WHITESPACE CHARACTERS
//find REF line
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber); // REMOVE UNWANTED WHITESPACE CHARACTERS
var_dump($refnumber);
if($refnumber != '')
{
$refnumber = '_'. $refnumber .'_';
$filerenamed = str_replace($find, $refnumber, $file);
copy($directory_with_files . DIRECTORY_SEPARATOR . $file, $dirname . DIRECTORY_SEPARATOR . $filerenamed);
}
echo $refnumber . "\n";
} // END IF
} // END WHILE READING FILE
fclose($handle);
}
} // END IF FILENAME MATCH
}
<?php
error_reporting(E_ALL);
// Some setup stuff
$find = '.5010.';
$dirname = 't1517/5010';
// Get list of files using glob with wildcard
$files = glob("t1517/*{$find}*");
//iterate collected files
foreach($files as $file) {
// Read all the lines in the file into an array
$lines = file($file);
// Iterate over the array of lines
foreach($lines as $line) {
// check if line contains search string
// using preg_match to check and extract
// reference at the same time
if (preg_match("/REF\*2U\*(.*?)\~/", $line, $match)) {
// glob uses full paths so extract the filename from
// the path
$newfile = basename(str_replace($find, "_{$match[1]}_", $file));
// Some debug code
echo "f: {$file}, NF: {$newfile}<br/>";
// And finally do the copy.
copy($file, "{$dirname}/{$newfile}");
}
}
}
EDIT... potential to grow ...Yes, exactly. If the instant answers do not solve the issues, these questions might be good candidates for E-E Gigs.
Please show us the file name that "doesn't open any more." Then we can probably show you a tested and working example.