感谢您抽出宝贵时间阅读本文,我将感谢每一个回复,而不是内容的质量.:)
使用php,我正在尝试创建一个脚本,根据行是否以0或负数开头,将删除文本文件(.txt)中的多行.文件中的每一行总是以数字开头,我需要删除所有中性和/或负数.
我正在努力的主要部分是文本文件中的内容不是静态的(例如,包含x个行/单词等).实际上,它每隔5分钟自动更新几行.因此,我希望删除所有包含中性或负数的行.
文本文件遵循以下结构:
-29 aullah1
0 name
4 username
4 user
6 player
如果可能的话,我会删除第1行和第2行,因为它以中性/负数开头.在某些时候,有时候有两个以上的中性/负数.
感谢所有的帮助,我期待着您的回复; 谢谢.:)如果我没有清楚地解释任何内容和/或您希望我更详细地解释,请回复.:)
谢谢.
例:
$file = file("mytextfile.txt");
$newLines = array();
foreach ($file as $line)
    if (preg_match("/^(-\d+|0)/", $line) === 0)
        $newLines[] = chop($line);
$newFile = implode("\n", $newLines);
file_put_contents("mytextfile.txt", $newFile);
重要的是你chop()将换行字符放在行尾,这样你就不会得到空的空格.测试成功.
我想这些线路上的东西,它是未经测试的.
$newContent = "";
$lines = explode("\n" , $content);
foreach($lines as $line){
  $fChar = substr($line , 0 , 1);
  if($fChar == "0" || $fChar == "-") continue;
  else $newContent .= $line."\n";
}
如果文件很大,最好逐行读取:
$fh_r = fopen("input.txt", "r");  // open file to read.
$fh_w = fopen("output.txt", "w"); // open file to write.
while (!feof($fh_r)) { // loop till lines are left in the input file.
        $buffer = fgets($fh_r); //  read input file line by line.
        // if line begins with num other than 0 or -ve num write it. 
        if(!preg_match('/^(0|-\d+)\b/',$buffer)) { 
                fwrite($fh_w,$buffer);
        }       
}       
fclose($fh_r);
fclose($fh_w);
注意:错误检查不包括在内.
file_put_contents($newfile, 
    implode(
        preg_grep('~^[1-9]~', 
            file($oldfile))));
php不是特别优雅,但仍然......
将整行加载到变量中,然后检查第一个字母是 - 还是0.
$newContent = "";
$lines = explode("\n" , $content);
foreach($lines as $line){
  $fChar = $line[0];
  if(!($fChar == '0' || $fChar == '-'))
  $newContent .= $line."\n";
}
我改变了malik的代码以获得更好的性能和质量.
| 归档时间: | 
 | 
| 查看次数: | 4123 次 | 
| 最近记录: |