>  기사  >  백엔드 개발  >  PHP는 텍스트 문서의 중복 줄을 처리합니다.

PHP는 텍스트 문서의 중복 줄을 처리합니다.

*文
*文원래의
2017-12-26 14:22:121457검색

PHP는 텍스트 문서에서 반복되는 줄을 어떻게 처리하나요? 본 글에서는 주로 PHP에서 텍스트 파일의 중복된 줄을 삭제하는 방법을 소개하고, PHP에서 텍스트 파일을 조작하는 관련 기술을 다루고 있습니다. 그것이 모두에게 도움이 되기를 바랍니다.

이 문서의 예에서는 PHP의 텍스트 파일에서 중복된 줄을 삭제하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 구체적인 분석은 다음과 같습니다.

이 PHP 함수는 파일에서 중복된 줄을 삭제하는 데 사용됩니다. 대소문자를 무시하고 개행 문자를 지정할지 여부를 지정할 수도 있습니다.


/**
 * RemoveDuplicatedLines
 * This function removes all duplicated lines of the given text file.
 *
 * @param   string
 * @param   bool
 * @return  string
 */
function RemoveDuplicatedLines($Filepath, $IgnoreCase=false, $NewLine="\n"){
  if (!file_exists($Filepath)){
    $ErrorMsg = 'RemoveDuplicatedLines error: ';
    $ErrorMsg .= 'The given file ' . $Filepath . ' does not exist!';
    die($ErrorMsg);
  }
  $Content = file_get_contents($Filepath);
  $Content = RemoveDuplicatedLinesByString($Content, $IgnoreCase, $NewLine);
  // Is the file writeable?
  if (!is_writeable($Filepath)){
    $ErrorMsg = 'RemoveDuplicatedLines error: ';
    $ErrorMsg .= 'The given file ' . $Filepath . ' is not writeable!';  
    die($ErrorMsg);
  }
  // Write the new file
  $FileResource = fopen($Filepath, 'w+');   
  fwrite($FileResource, $Content);    
  fclose($FileResource);  
}
 
/**
 * RemoveDuplicatedLinesByString
 * This function removes all duplicated lines of the given string.
 *
 * @param   string
 * @param   bool
 * @return  string
 */
function RemoveDuplicatedLinesByString($Lines, $IgnoreCase=false, $NewLine="\n"){
  if (is_array($Lines))
    $Lines = implode($NewLine, $Lines);
  $Lines = explode($NewLine, $Lines);
  $LineArray = array();
  $Duplicates = 0;
  // Go trough all lines of the given file
  for ($Line=0; $Line < count($Lines); $Line++){
    // Trim whitespace for the current line
    $CurrentLine = trim($Lines[$Line]);
    // Skip empty lines
    if ($CurrentLine == &#39;&#39;)
      continue;
    // Use the line contents as array key
    $LineKey = $CurrentLine;
    if ($IgnoreCase)
      $LineKey = strtolower($LineKey);
    // Check if the array key already exists,
    // if not add it otherwise increase the counter
    if (!isset($LineArray[$LineKey]))
      $LineArray[$LineKey] = $CurrentLine;    
    else        
      $Duplicates++;
  }
  // Sort the array
  asort($LineArray);
  // Return how many lines got removed
  return implode($NewLine, array_values($LineArray));  
}


사용 예:


// Example 1
// Removes all duplicated lines of the file definied in the first parameter.
$RemovedLinesCount = RemoveDuplicatedLines(&#39;test.txt&#39;);
print "Removed $RemovedLinesCount duplicate lines from the test.txt file.";
// Example 2 (Ignore case)
// Same as above, just ignores the line case.
RemoveDuplicatedLines(&#39;test.txt&#39;, true);
// Example 3 (Custom new line character)
// By using the 3rd parameter you can define which character
// should be used as new line indicator. In this case
// the example file looks like &#39;foo;bar;foo;foo&#39; and will
// be replaced with &#39;foo;bar&#39; 
RemoveDuplicatedLines(&#39;test.txt&#39;, false, &#39;;&#39;);

관련 권장 사항:

PHP 파일 읽기 fread, fgets, fgetc, file_get_contents 및 파일 기능 사용 예제 코드

PHP 파일 잠금에 대한 간략한 이야기

PHP 파일 탐색

위 내용은 PHP는 텍스트 문서의 중복 줄을 처리합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.