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 == '')
      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('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程序设计有所帮助。

(0)

相关推荐

  • PHP实现逐行删除文件右侧空格的方法 原创

    本文实例讲述了PHP实现逐行删除文件右侧空格的方法.分享给大家供大家参考,具体如下: 在编辑整理代码的过程中发现网上的一些代码经常会有不少的右侧空格,偶尔会影响到代码的排版与阅读,所以写了一段简单的php代码来逐行删除文件右侧的空格,并保存到新的文件中. 带有右侧空格的demo.txt文件(该文件是PHP逐行读取功能代码)如下: $file = fopen("welcome.txt", "r") or exit("Unable to open file!&

  • php删除左端与右端空格的方法

    本文实例讲述了php删除左端与右端空格的方法.分享给大家供大家参考.具体方法如下: 在php中删除函数比js要具体很多,除了trim()函数,还有ltrim()和rtrim()函数,他们分别要删除前后左右的空格了,除了这三个函数还可以使用正则删除. ltrim()函数:ltrim($str, $charlist) $str表示被处理的字符串,$charlist是要删除的特殊字符,若为空则去除左端的空格,代码如下: 复制代码 代码如下: <?php   $t=" ...I'm Jacky..

  • php写入、删除与复制文件的方法

    本文实例讲述了php写入.删除与复制文件的方法.分享给大家供大家参考.具体如下: 1. 写入: <?php $filename = "Test//file.txt"; $file = fopen($filename, "w"); //以写模式打开文件 fwrite($file, "Hello, world!/n"); //写入第一行 fwrite($file, "This is a test!/n"); //写入第二行

  • php中ltrim()、rtrim()与trim()删除字符空格实例

    本文实例讲述了php中ltrim().rtrim()与trim()删除字符空格的方法.分享给大家供大家参考.具体分析如下: php中的trim函数不能像asp中的一样,可以自动删除所有空格,PHP专业提供了 rtrim() trim()函数,对此感兴趣的朋友可以参考一下. PHP实例代码如下: 复制代码 代码如下: <?php $str=" 去除前后空格 "; echo "方括号中为原始字符串:[".$str."]<br>";

  • PHP FTP操作类代码( 上传、拷贝、移动、删除文件/创建目录)

    复制代码 代码如下: <?php/*** 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 )* 时间:2006/5/9* 作者:欣然随风* QQ:276624915*/class class_ftp{    public $off; // 返回操作状态(成功/失败)    public $conn_id; // FTP连接    /**     * 方法:FTP连接     * @FTP_HOST -- FTP主机     * @FTP_PORT -- 端口     * @FTP_USER

  • php中3种方法删除字符串中间的空格

    第一种:使用正则 复制代码 代码如下: <?phpecho preg_replace('# #', '', 'ab     ab');//输出 "abab"?> 第二种:使用str_replace()函数 复制代码 代码如下: <?phpecho str_replace(' ', '', 'ab    ab');//输出 "abab'?> 第三种:使用strtr()函数 复制代码 代码如下: <?phpecho strtr('ab    ab',

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

    本文实例讲述了php删除文本文件中重复行的方法.分享给大家供大家参考.具体分析如下: 这个php函数用来删除文件中的重复行,还可以指定是否忽略大小写,和指定换行符 /** * RemoveDuplicatedLines * This function removes all duplicated lines of the given text file. * * @param string * @param bool * @return string */ function RemoveDupl

  • shell中删除文件中重复行的方法

    Linux下文本处理工具很丰富很强大,例如这样一个文件: 复制代码 代码如下: cat log www.jb51.net 192.168.1.1www.jb51.net 192.168.1.1www.jb51.net 192.168.1.2ffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeefffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeggggggggggggggg

  • Java基础之删除文本文件中特定行的内容

    一.问题的产生 基于I/O流编写的图书馆管理系统 在最近使用I/O流写图书馆管理系统中管理员对图书和用户的管理操作时,遇到了需要删除特定图书和用户的操作,在查询资料和询问老师后得知I/O流中没有可以直接删除单独行的方法. 二.解决思路 同时也为我提供了新的思路:将整个文件中的全部内容读取出来,然后通过集合将每一行单独存放,通过查找到集合内特定的内容后,将该行内容删除,此时list集合会自动将后面的内容填补上来,再重新写入的时候不会出现空行的情况.这时再重新遍历一次该集合,将现在的集合内容写入文件

  • python删除列表中重复记录的方法

    本文实例讲述了python删除列表中重复记录的方法.分享给大家供大家参考.具体实现方法如下: def removeListDuplicates(seq): seen = set() seen_add = seen.add return [ x for x in seq if x not in seen and not seen_add(x) ] 希望本文所述对大家的Python程序设计有所帮助.

  • C#删除字符串中重复字符的方法

    本文实例讲述了C#删除字符串中重复字符的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: #region 删除重复字符  string s = "sdfffffsrlkjesgljfdg03940864e5=_0R9DTGR98YUI\\|||'\\???fdf///";  Response.Write("<br/>String:" + s + "<br/>Result:");  IEnumerable

  • 利用Python删除电脑中重复文件的方法

    目录 前言 练习 代码演示 总结 前言 在生活中,我们经常会遇到电脑中文件重复的情况.在文件较少的情况下,这类情况还比较容易处理,最不济就是一个个手动对比删除:而在重复文件很多的时候,我们很难保证把重复文件全部删完.下面文章就来简单介绍便捷一个小方法,用Python来删除重复文件 练习 Python提供一个内置电脑文件管理库os模块,我们可以利用它来删除多余文件. 当一个文档里存在重复文件名,我们的系统会自动给我们重复的文件名更名, 比如下图的文件“1”重复了3次:  那我们该怎么删除文件“1”

  • php删除数组中重复元素的方法

    几种php删除数组元素方法在很多情况下我们的数组会出现重复情况,那我们删除数组中一些重复的内容怎么办,这些元素必须保持他唯一,所以就想办法来删除它们,下面利用了遍历查询来删除重复数组元素的几种方法. 方法一.完整删除重复数组实例-----删除数组中的一个元素 function array_remove_value(&$arr, $var){ foreach ($arr as $key => $value) { if (is_array($value)) { array_remove_valu

  • python筛选出两个文件中重复行的方法

    本文实例为大家分享了python脚本筛选出两个文件中重复的行数,供大家参考,具体内容如下 ''' 查找A文件中,与B文件中内容不重复的内容 ''' #!usr/bin/python import sys import os ''' 字符串查找函数,使用二分查找法在列表中进行查询 ''' def binarySearch(value, lines): right = len(lines) - 1 left = 0 a = value.strip() while left <= right: mid

  • C#遍历删除字符串中重复字符

    本文实例讲述了C#遍历删除字符串中重复字符的方法.分享给大家供大家参考.具体实现方法如下: Func<string, string> RemoveDuplicate = delegate(string s) { BitArray _arr = new BitArray(256); StringBuilder _sb = new StringBuilder(); s = s.ToLower(); for (int i = 0; i < s.Length; i++) { if (_arr[(

  • python统计一个文本中重复行数的方法

    本文实例讲述了python统计一个文本中重复行数的方法.分享给大家供大家参考.具体实现方法如下: 比如有下面一个文件 2 3 1 2 我们期望得到 2,2 3,1 1,1 解决问题的思路: 出现的文本作为key, 出现的数目作为value,然后按照value排除后输出 最好按照value从大到小输出出来,可以参照: 复制代码 代码如下: in recent Python 2.7, we have new OrderedDict type, which remembers the order in

随机推荐