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作的文本留言本的例子(六)
Oct 09 PHP
php.ini中date.timezone设置分析
Jul 29 PHP
mysql,mysqli,PDO的各自不同介绍
Sep 19 PHP
php导入csv文件碰到乱码问题的解决方法
Feb 10 PHP
php中把美国时间转为北京时间的自定义函数分享
Jul 28 PHP
php字符串截取函数用法分析
Nov 25 PHP
PHP简单实现文本计数器的方法
Apr 28 PHP
PHP CURL与java http使用方法详解
Jan 26 PHP
PHP抽象类基本用法示例
Dec 28 PHP
php+Ajax处理xml与json格式数据的方法示例
Mar 04 PHP
PHP中-&gt;和=&gt;的含义及使用示例解析
Aug 06 PHP
php7连接MySQL实现简易查询程序的方法
Oct 13 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
Zend Framework分发器用法示例
2016/12/11 PHP
PHP的Trait机制原理与用法分析
2019/10/18 PHP
PHP code 验证码生成类定义和简单使用示例
2020/05/27 PHP
js类后台管理菜单类-MenuSwitch
2007/09/12 Javascript
JavaScript 设计模式学习 Factory
2009/07/29 Javascript
jquery解析XML字符串和XML文件的方法说明
2014/02/21 Javascript
用于deeplink的js方法(判断手机是否安装app)
2014/04/02 Javascript
基于豆瓣API+Angular开发的web App
2015/01/02 Javascript
Ajax中解析Json的两种方法对比分析
2015/06/25 Javascript
用JavaScript实现PHP的urlencode与urldecode函数
2015/08/13 Javascript
JS采用绝对定位实现回到顶部效果完整实例
2016/06/20 Javascript
JavaScript 函数模式详解及示例
2016/09/07 Javascript
JavaScript中日常收集常见的10种错误(推荐)
2017/01/08 Javascript
详解vue2 $watch要注意的问题
2017/09/08 Javascript
JavaScript 装逼指南(js另类写法)
2020/05/10 Javascript
javascript实现点击小图显示大图
2020/11/29 Javascript
[01:19:34]2014 DOTA2国际邀请赛中国区预选赛 New Element VS Dream time
2014/05/22 DOTA
python实现异步回调机制代码分享
2014/01/10 Python
python的多重继承的理解
2017/08/06 Python
Python 多线程的实例详解
2017/09/07 Python
python常用数据重复项处理方法
2019/11/22 Python
pytorch实现seq2seq时对loss进行mask的方式
2020/02/18 Python
python opencv进行图像拼接
2020/03/27 Python
Django {{ MEDIA_URL }}无法显示图片的解决方式
2020/04/07 Python
Matlab中plot基本用法的具体使用
2020/07/17 Python
Mytheresa英国官网:拥有160多个奢侈品品牌
2016/10/09 全球购物
POS解决方案:MUNBYN(热敏打印机、条形码扫描仪)
2020/06/09 全球购物
冰淇淋店的创业计划书
2014/02/07 职场文书
上班玩手机检讨书
2014/02/17 职场文书
学习礼仪心得体会
2014/09/01 职场文书
城市规划应届生推荐信
2014/09/08 职场文书
2014大学生职业生涯规划书最新范文
2014/09/13 职场文书
2014年幼儿园工作总结
2014/11/10 职场文书
青年文明号创建口号大全
2015/12/25 职场文书
pandas中DataFrame数据合并连接(merge、join、concat)
2021/05/30 Python
baselines示例程序train_cartpole.py的ImportError
2022/05/20 Python