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的memory_limit限制的方法分享
Feb 21 PHP
探讨:使用XMLSerialize 序列化与反序列化
Jun 08 PHP
探讨:如何使用PHP实现计算两个日期间隔的年、月、周、日数
Jun 13 PHP
php文件服务实现虚拟挂载其他目录示例
Apr 17 PHP
浅析php中json_encode()和json_decode()
May 25 PHP
在SAE上搭建最新wordpress的方法
Dec 21 PHP
腾讯微博提示missing parameter errorcode 102 错误的解决方法
Dec 22 PHP
php计算函数执行时间的方法
Mar 20 PHP
百度工程师讲PHP函数的实现原理及性能分析(一)
May 13 PHP
PHP5.2中PDO的简单使用方法
Mar 25 PHP
PHP基于双向链表与排序操作实现的会员排名功能示例
Dec 26 PHP
Laravel5.0+框架邮件发送功能实现方法图文与实例详解
Apr 23 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系统命令函数使用分析
2013/07/05 PHP
PHP封装的HttpClient类用法实例
2015/06/17 PHP
PHPCMS忘记后台密码的解决办法
2016/10/30 PHP
仅用[]()+!等符号就足以实现几乎任意Javascript代码
2010/03/01 Javascript
JavaScript实现在数组中查找不同顺序排列的字符串
2014/09/26 Javascript
express的中间件basicAuth详解
2014/12/04 Javascript
jquery事件preventDefault()方法用法实例
2015/01/16 Javascript
javascript中call apply 的应用场景
2015/04/16 Javascript
AngularJS学习笔记之基本指令(init、repeat)
2015/06/16 Javascript
JavaScript实现同一页面内两个表单互相传值的方法
2015/08/12 Javascript
jQuery蓝色风格滑动导航栏代码分享
2015/08/19 Javascript
jQuery 中ajax异步调用的四种方式
2016/06/28 Javascript
easyui-datagrid开发实践(总结)
2017/08/02 Javascript
微信小程序文字显示换行问题
2019/07/28 Javascript
基于layui内置模块(element常用元素的操作)
2019/09/20 Javascript
微信小程序实现下滑到底部自动翻页功能
2020/03/07 Javascript
[03:23]我的刀塔你不可能这么可爱 第一期金萌萌的故事
2014/06/20 DOTA
[01:16:28]DOTA2-DPC中国联赛 正赛 iG vs Magma BO3 第二场 2月23日
2021/03/11 DOTA
Python3.0与2.X版本的区别实例分析
2014/08/25 Python
Python3.x中自定义比较函数
2015/04/24 Python
Python3爬虫学习入门教程
2018/12/11 Python
使用PyCharm进行远程开发和调试的实现
2019/11/04 Python
keras 实现轻量级网络ShuffleNet教程
2020/06/19 Python
墨西哥运动服饰和鞋网上商店:Netshoes墨西哥
2016/07/28 全球购物
印尼披萨外送专家:Domino’s Pizza印尼
2017/12/28 全球购物
西班牙拥有最佳品牌的动物商店:Animalear.com
2018/01/05 全球购物
GUESS Factory加拿大:牛仔裤、服装及配饰
2019/09/20 全球购物
中专药剂专业应届毕的自我评价
2013/12/27 职场文书
保密承诺书
2014/03/27 职场文书
个人投资计划书
2014/05/01 职场文书
2014年机关党委工作总结
2014/12/11 职场文书
毕业论文指导教师评语
2014/12/30 职场文书
董事长致辞
2015/07/29 职场文书
酒店工程部的岗位职责汇总大全
2019/10/23 职场文书
你离财务总监还有多远?速览CFO的岗位职责
2019/11/18 职场文书
php 获取音视频时长,PHP 利用getid3 获取音频文件时长等数据
2021/04/01 PHP