我有一个PHP脚本,它根据文件名获取文本文件的内容,使用正则表达式进行一系列查找和替换,然后将清理后的文件输出到另一个文件夹。
代码如下所示,供参考:
<?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');
?>
可能有一些方法可以清理它,但现在它可以工作。
我们的想法是每天都会以不同的方式命名原始文本文件('GlobalTest02122019.txt','20190213Global.txt'等),然后将其放在标记为IN的文件夹中。
我的问题是,有没有办法让任何文本文件的内容被删除在这个IN文件夹中,无论名称是什么?此工作流程的理想方式是不必重命名任何文件。
还有,有办法将文件输出到OUT文件夹并保留原始文件名吗?
您可以提供的任何输入将不胜感激。我试着查看过去的问题但是找不到类似于我正在寻找的东西。
如果它将是目录中唯一的文件,或者如果有一个模式可以匹配以隔离它(即,它是唯一以“Global”开头的文件)那么glob()
函数将使您到达那里。基本上它返回一个文件/目录数组,匹配“传统”通配符样式的引用,就像你用ls
或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:~$
使用glob()
拉入可能的文件列表,遍历数组查找文件模式(或处理每个文件,或者根据需要处理唯一的文件等),当发现调用您的过程函数时,将其传递给现在已知的非通配文件路径。