찾다
php教程php手册php删除文本文件中重复行的方法

php删除文本文件中重复行的方法

   php删除文本文件中重复行的方法

        本文实例讲述了php删除文本文件中重复行的方法。分享给大家供大家参考。具体分析如下:

  这个php函数用来删除文件中的重复行,还可以指定是否忽略大小写,和指定换行符

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

/**

* 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

// Trim whitespace for the current line

$CurrentLine = trim($Lines[$Line]);

// Skip empty lines

if ($CurrentLine == '')

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));

}

  使用范例:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

// Example 1

// Removes all duplicated lines of the file definied in the first parameter.

$RemovedLinesCount = RemoveDuplicatedLines('test.txt');

print "Removed $RemovedLinesCount duplicate lines from the test.txt file.";

// Example 2 (Ignore case)

// Same as above, just ignores the line case.

RemoveDuplicatedLines('test.txt', 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 'foo;bar;foo;foo' and will

// be replaced with 'foo;bar'

RemoveDuplicatedLines('test.txt', false, ';');

  希望本文所述对大家的php程序设计有所帮助。

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

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기