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的session cookie错误
Aug 09 PHP
php+mysql 实现身份验证代码
Mar 24 PHP
php版小黄鸡simsimi聊天机器人接口分享
Jan 26 PHP
php判断电脑访问、手机访问的例子
May 10 PHP
thinkphp视图模型查询提示ERR: 1146:Table 'db.pr_order_view' doesn't exist的解决方法
Oct 30 PHP
使用PHP similar text计算两个字符串相似度
Nov 06 PHP
Symfony2学习笔记之插件格式分析
Mar 17 PHP
Redis构建分布式锁
Mar 28 PHP
PHP封装的验证码工具类定义与用法示例
Aug 22 PHP
laravel异步监控定时调度器实例详解
Jun 21 PHP
浅谈PHP5.6 与 PHP7.0 区别
Oct 09 PHP
YII2框架中日志的配置与使用方法实例分析
Mar 18 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默认安装产生系统漏洞
2006/10/09 PHP
echo(),print(),print_r()之间的区别?
2006/11/19 PHP
支持中文的php加密解密类代码
2011/11/27 PHP
php FLEA中二叉树数组的遍历输出
2012/09/26 PHP
PHP常见数组排序方法小结
2018/08/20 PHP
javascript 解析后的xml对象的读取方法细解
2009/07/25 Javascript
jquery 动态合并单元格的实现方法
2016/08/26 Javascript
JavaScript实现数组降维详解
2017/01/05 Javascript
JS实现线性表的顺序表示方法示例【经典数据结构】
2017/04/11 Javascript
JS仿淘宝搜索框用户输入事件的实现
2017/06/19 Javascript
Node.js中流(stream)的使用方法示例
2017/07/16 Javascript
ReactNative踩坑之配置调试端口的解决方法
2017/07/28 Javascript
Bootstrap Table快速完美搭建后台管理系统
2017/09/20 Javascript
vue使用axios跨域请求数据问题详解
2017/10/18 Javascript
jQuery获取所有父级元素及同级元素及子元素的方法(推荐)
2018/01/21 jQuery
详解处理bootstrap4不支持远程静态框问题
2018/07/20 Javascript
Python中Numpy mat的使用详解
2019/05/24 Python
浅析Python语言自带的数据结构有哪些
2019/08/27 Python
Pytorch在dataloader类中设置shuffle的随机数种子方式
2020/01/14 Python
Django中modelform组件实例用法总结
2020/02/10 Python
东南亚排名第一的服务市场:kaodim
2019/03/28 全球购物
自荐信格式范文
2013/10/07 职场文书
全陪导游欢迎词
2014/01/17 职场文书
协议书怎么写
2014/04/21 职场文书
捐助贫困学生倡议书
2014/05/16 职场文书
社会工作专业求职信
2014/07/15 职场文书
支行行长竞聘报告
2014/11/06 职场文书
2014年学生会生活部工作总结
2014/11/07 职场文书
检讨书格式
2015/01/23 职场文书
自我工作评价范文
2015/03/06 职场文书
故意伤害罪辩护词
2015/05/21 职场文书
新教师2015年度工作总结
2015/07/22 职场文书
暑假生活随笔
2015/08/15 职场文书
成人成长感言如何写?
2019/08/16 职场文书
详解MySQL中的主键与事务
2021/05/27 MySQL
gtx1650怎么样 gtx1650显卡相当于什么级别
2022/04/08 数码科技