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


Posted in PHP onApril 28, 2015

本文实例讲述了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程序设计有所帮助。

PHP 相关文章推荐
如何隐藏你的.php文件
Jan 04 PHP
基于Windows下Apache PHP5.3.1安装教程
Jan 08 PHP
php+mysql事务rollback&amp;commit示例
Feb 08 PHP
PHP XML error parsing SOAP payload on line 1
Jun 17 PHP
php获取$_POST同名参数数组的实现介绍
Jun 30 PHP
PHP使用Session遇到的一个Permission denied Notice解决办法
Jul 30 PHP
php数字每三位加逗号的功能函数
Oct 22 PHP
PHP函数引用返回的实例详解
Sep 11 PHP
Zend Framework框架实现类似Google搜索分页效果
Nov 25 PHP
CI框架(CodeIgniter)公共模型类定义与用法示例
Aug 10 PHP
PHP7中I/O模型内核剖析详解
Apr 14 PHP
PHP连接MySQL数据库的三种方式实例分析【mysql、mysqli、pdo】
Nov 04 PHP
php实现简单的语法高亮函数实例分析
Apr 27 #PHP
php转换颜色为其反色的方法
Apr 27 #PHP
PHP结合jQuery.autocomplete插件实现输入自动完成提示的功能
Apr 27 #PHP
PHP+jQuery+Ajax实现用户登录与退出
Apr 27 #PHP
php使用cookie实现记住用户名和密码实现代码
Apr 27 #PHP
php使用cookie实现记住登录状态
Apr 27 #PHP
php curl请求信息和返回信息设置代码实例
Apr 27 #PHP
You might like
php生成静态页面的简单示例
2014/04/17 PHP
手把手编写PHP框架 深入了解MVC运行流程
2016/09/19 PHP
php使用PDO获取结果集的方法
2017/02/16 PHP
Thinkphp开发--集成极光推送
2017/09/15 PHP
PHPStorm2020.1永久激活及下载更新至2020(推荐)
2020/09/25 PHP
javascrip客户端验证文件大小及文件类型并重置上传
2011/01/12 Javascript
jquery加载页面的方法(页面加载完成就执行)
2011/06/21 Javascript
javascript移出节点removeChild()使用介绍
2014/04/03 Javascript
JavaScript fontcolor方法入门实例(按照指定的颜色来显示字符串)
2014/10/17 Javascript
基于Bootstrap实现tab标签切换效果
2020/04/15 Javascript
Angular懒加载机制刷新后无法回退的快速解决方法
2016/08/30 Javascript
关于vue.js v-bind 的一些理解和思考
2017/06/06 Javascript
深入解析nodejs HTTP服务
2017/07/25 NodeJs
vue.js声明式渲染和条件与循环基础知识
2017/07/31 Javascript
基于canvas粒子系统的构建详解
2017/08/31 Javascript
VUE2实现事件驱动弹窗示例
2017/10/21 Javascript
taro开发微信小程序的实践
2019/05/21 Javascript
使用Python读写文本文件及编写简单的文本编辑器
2016/03/11 Python
删除python pandas.DataFrame 的多重index实例
2018/06/08 Python
Python函数装饰器常见使用方法实例详解
2019/03/30 Python
Django中使用 Closure Table 储存无限分级数据
2019/06/06 Python
Python CVXOPT模块安装及使用解析
2019/08/01 Python
python实现的分析并统计nginx日志数据功能示例
2019/12/21 Python
简单了解django文件下载方式
2020/02/10 Python
appium+python adb常用命令分享
2020/03/06 Python
django queryset 去重 .distinct()说明
2020/05/19 Python
python实现猜单词游戏
2020/05/22 Python
澳大利亚体育和露营装备在线/实体零售商:Find Sports
2020/06/03 全球购物
完美实现CSS垂直居中的11种方法
2021/03/27 HTML / CSS
田径运动会开幕式及主持词
2014/03/28 职场文书
关于读书的演讲稿500字
2014/08/27 职场文书
民用住房租房协议书
2014/10/29 职场文书
总经理岗位职责范本
2015/04/01 职场文书
公司仓库管理制度
2015/08/04 职场文书
JavaScript 事件捕获冒泡与捕获详情
2021/11/11 Javascript
SpringBoot详解整合Redis缓存方法
2022/07/15 Java/Android