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 和 MYSQL
Oct 09 PHP
深思 PHP 数组遍历的差异(array_diff 的实现)
Mar 23 PHP
php面向对象全攻略 (七) 继承性
Sep 30 PHP
php中3des加密代码(完全与.net中的兼容)
Aug 02 PHP
PHP高手需要要掌握的知识点
Aug 21 PHP
Yii获取当前url和域名的方法
Jun 08 PHP
33道php常见面试题及答案
Jul 06 PHP
PHP程序中使用adodb连接不同数据库的代码实例
Dec 19 PHP
PHP的swoole扩展安装方法详细教程
May 18 PHP
利用PHP访问带有密码的Redis方法示例
Feb 09 PHP
php使用Jpgraph创建折线图效果示例
Feb 15 PHP
PHP explode()函数用法讲解
Feb 15 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
对于ThinkPHP框架早期版本的一个SQL注入漏洞详细分析
2014/07/04 PHP
php实现中文字符截取防乱码方法汇总
2015/04/29 PHP
WordPress中给文章添加自定义字段及后台编辑功能区域
2015/12/19 PHP
[原创]smarty简单模板变量输出方法
2016/07/09 PHP
学习YUI.Ext第七日-View&amp;JSONView Part Two-一个画室网站的案例
2007/03/10 Javascript
js有关元素内容操作小结
2011/12/20 Javascript
js设置cookie过期当前时间减去一秒相当于立即过期
2014/09/04 Javascript
js实现分享到随页面滚动而滑动效果的方法
2015/04/10 Javascript
微信小程序开发之数据存储 参数传递 数据缓存
2017/04/13 Javascript
解决jQuery使用append添加的元素事件无效的问题
2018/08/30 jQuery
JS获取今天是本月第几周、本月共几周、本月有多少天、是今年的第几周、是今年的第几天的示例代码
2018/12/05 Javascript
React性能优化系列之减少props改变的实现方法
2019/01/17 Javascript
Vue解析带html标签的字符串为dom的实例
2019/11/13 Javascript
vue中使用elementUI组件手动上传图片功能
2019/12/13 Javascript
JavaScript实现好看的跟随彩色气泡效果
2020/02/06 Javascript
Vue实现简易计算器
2020/02/25 Javascript
Vue中通过属性绑定为元素绑定style行内样式的实例代码
2020/04/30 Javascript
Vue项目接入Paypal实现示例详解
2020/06/04 Javascript
javascript中正则表达式语法详解
2020/08/07 Javascript
TypeScript魔法堂之枚举的超实用手册
2020/10/29 Javascript
Python爬取网易云音乐热门评论
2017/03/31 Python
在python plt图表中文字大小调节的方法
2019/07/08 Python
搭建python django虚拟环境完整步骤详解
2019/07/08 Python
安装并免费使用Pycharm专业版(学生/教师)
2020/09/24 Python
matplotlib 范围选区(SpanSelector)的使用
2021/02/24 Python
canvas实现手机的手势解锁的步骤详细
2020/03/16 HTML / CSS
Staples加拿大官方网站:办公用品一站式采购
2016/09/25 全球购物
波兰最大的度假胜地和城市公寓租赁运营商:Sun & Snow
2018/10/18 全球购物
馥蕾诗美国官网:Fresh美国
2019/10/09 全球购物
工作评语大全
2014/04/26 职场文书
民生工作实施方案
2014/05/31 职场文书
医院标语大全
2014/06/23 职场文书
护士个人年度总结范文
2015/02/13 职场文书
化验室岗位职责
2015/02/14 职场文书
求职自我评价怎么写
2015/03/09 职场文书
MySQL表的增删改查基础教程
2021/04/07 MySQL