I have a PHP script that gets the contents of a text file based on the filename, makes a series of find and replaces using regular expressions, and then outputs the cleaned up file to another folder.
The code looks like this, for reference:
<?php
$test = file_get_contents('GlobalTest.txt');
$test1 = preg_replace('/[\r\n]+/', "\r\n", $test);
$result = preg_replace('/;\w+;\d+;\d+%.+/m', '', $test1);
$resulta = preg_replace('/^((?!Athens|Baghdad|Hong Kong|Jerusalem|London|Mexico City|Moscow|Paris|Rio de Janeiro|Rome|Tokyo|Global Forecast|~_~_~_~_~_).)*$/m', '', $result);
$resultb = preg_replace('/^(?:[\t]*(?:\r?\n|\r))+/m', '', $resulta);
$resultc = preg_replace('/;.+\D;/m', ';', $resultb);
$resultd = preg_replace('/^(.*?);(?=.*;)/m', '$1 ', $resultc);
$resulte = preg_replace('/;/m', '/', $resultd);
$resultf = preg_replace('/<e0>/m', '', $resulte);
file_put_contents('/Users/asage/Desktop/Forecast/OUT/Output Global Test.txt', $resultf);
unlink ('GlobalTest.txt');
?>
There's probably ways to clean this up a bit, but it works for now.
The idea is that the raw text file is going to be named differently every day ('GlobalTest02122019.txt', '20190213Global.txt', etc.), and then dropped in a folder labeled IN.
My question is, is there a way to get the contents of whatever text file is dropped in this IN folder, regardless of the name? The ideal way for this workflow would be to not have to rename any of the files.
Also, is there a way to output the file into the OUT folder and keep the original filename?
Any input you can provide would be greatly appreciated. I tried looking through past questions but wasn't able to find anything similar to what I'm looking for.
If it will either be the only file in the directory, or if there will be a pattern you can match to isolate it (ie, it is the only file that starts with "Global") then the glob()
function will get you there. Basically it returns an array of files/directories that match "traditional" wildcard-style references like you'd get with ls
or dir
ivan@darkstar:~$ ls t
file1 file2
ivan@darkstar:~$ cat e.php
<?php
$files=glob("./t/*");
print_r($files);
?>
ivan@darkstar:~$ php e.php
Array
(
[0] => ./t/file1
[1] => ./t/file2
)
ivan@darkstar:~$
Pull in your list of possible files with glob()
, loop through the array looking for your file pattern (or process every file, or process the only file, etc as appropriate) and when found call your process function, passing it the now known non-wildcarded file path.