【发布时间】:2013-12-10 15:46:34
【问题描述】:
我需要在一组文件中更新同一行,其中还包括dd/mm/yyyy 格式的日期以及一些字符串。我在这里检查了对类似问题的答案,但是无法使任何建议的模式在我的代码中运行。
我当前的 PHP 代码是:
<?php
// get the system date
$sysdate = date("d/m/Y");
// open the directory
$dir = opendir($argv[1]);
$files = array();
// sorts the files alphabetically
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
// for each ordered file will run the in the clauses part
foreach ($files as $file) {
$lines = '';
// filename extension is '.hql'
if (strpos($file,".hql") != false || strpos($file,".HQL") != false)
{
$procfile = $argv[1] . '\\' . $file;
echo "Converting filename: " . $procfile . "\n";
$handle = fopen($procfile, "r");
$lines = fread($handle, filesize($procfile));
fclose($handle);
$string = $lines;
// What are we going to change runs in here
$pattern = '[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]';
$replacement = $sysdate;
$lines = preg_replace($pattern, $replacement, $string);
echo $lines;
$newhandle = fopen($procfile, 'w+');
fwrite($newhandle, $lines);
fclose($newhandle);
// DONE
}
}
closedir($dir);
?>
当我在命令提示符下运行此代码时,它没有给出任何错误消息,并且似乎运行正常。但是一旦它完成并检查我的文件,我发现每个文件的内容都被删除了,它们都变成了 0 KB 的文件,其中没有任何内容。
【问题讨论】: