簡體   English   中英

刪除類似的行-PHP

[英]Delete similar lines - PHP

是否可以刪除所有具有相同前30個字符的行,然后僅刪除具有這些字符的第一行?

例:

xx2 Lorem ipsum dolor sit amet, fdsfdsfs
xx2 Lorem ipsum dolor sit amet, 43434343

第二個應該刪除...希望有可能...謝謝

$page = explode( "\n", $file );
$count = 0;
foreach( $page as $line )
{
  if( in_array( substr( $line, 0, 30 ), $search ) ){
    unset( $page[$count] );  // delete the duplicate..
  }else{
    $search[] = substr( $line, 0, 30 );
  }
  $count++;
}

基本上,它需要一個文件或多行字符串,並逐行循環遍歷文件。 如果遇到了前30個字符,則會刪除該行。 如果還沒有,則將其添加到要檢查的列表中。 完成循環遍歷文件后,每個唯一的起始字符串將只有一個實例。 試試看,祝你好運。

如果您需要處理非常大的文件,則一次只讀取一行並寫入臨時文件將消耗更少的內存。 使用臨時文件並在完成后將其重命名為輸入文件將自動執行該操作,而不會丟失原始文件。 由於索引了鍵,因此檢查數組鍵而不是值將提供快速查找。 您還需要處理在substr上返回false的空白行的邊緣情況。

<?php
$infile_name = "infile.txt";

$seen = array();
$infile = fopen($infile_name, "r");
if ( $infile !== false ) {
    // Temporary file to write results to
    $outfile_name = tempnam(sys_get_temp_dir(), 'tmp');
    $outfile = fopen($outfile_name, "w");

    while (!feof($infile)) {
        $line = fgets($infile);
        if ( $line == '' ) {
            // blank line, just write it
            fwrite($outfile, $line);
        }
        else {
            $prefix = substr( $line, 0, 30 );

            if ( !array_key_exists($prefix, $seen) ) {
               fwrite($outfile, $line);

               // Store the prefix as a key for fast indexed lookup
               $seen[$prefix] = true;
            }
        }
    }

    fclose($infile);
    fclose($outfile);

    // Remove the old file and put the new file in its place
    unlink($infile_name);
    rename($outfile_name, $infile_name);
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM