【问题标题】:Remove line of file1 that exist on file2删除 file2 上存在的 file1 行
【发布时间】:2016-03-26 03:04:04
【问题描述】:

我想从 FILE2 中删除 FILE1 上的所有行。

我尝试使用此代码,但没有成功:

功能:

function removeit($searchfor, $file) {
   $file1 = fopen($file, "r") or exit("Unable to openfile!");
   $t="";
   while(!feof($file1)) {
      $k= fgets($file1);
      $pattern = preg_quote($searchfor, '/');
      $pattern = "/^.*$pattern.*\$/m";
      if ( preg_match($pattern, $k))
      {}
      else {
         $t=$t.$k;
      }
   }

   fclose($file1);
   $file = fopen($file, "w") or exit("Unable to open file!");
   fwrite($file,$t);
   fclose($file);
}

完成这项工作的代码:

$file = fopen("file1.txt", "r");
while(!feof($file)) {
   $line = fgets($file);
   # do same stuff with the $line
   echo removeit(trim($line), 'file2.txt');
}
fclose($file);

请对此代码进行任何修复?还是您有其他方法可以正确完成这项工作? 我尝试了各种代码以获得正确的结果,但我尝试的所有方法都没有成功。

FILE2 上的 FILE1 行不包含在整行中!

这里是一个例子:

文件 1:

AAA
BBB
CCC
DDD

这里是 FILE2:

555AAAPPP // This line contain AAA line1 of FILE1 (To remove)
MMMBBBEEE // This contain BBB (To remove)
111CCC333 // This contain CCC (To remove)
DD15568 // This line will not be removed because not present on FILE1

并且代码必须让代码保持原样,只需要删除行。

【问题讨论】:

  • 你的问题我不清楚:你想删除555AAAPPP吗?
  • 是的,这三行都必须删除,因为它包含 FILE1 的行:)
  • Erk,请不要这样做:$file = fopen($file, "w") -- 您正在更改变量的类型。而是使用类似$filename 的字符串和$file 的句柄。令人困惑。
  • 顺便说一句,您可以将该正则表达式简化为 $pattern = "/"+$pattern+"/";^.*.*$ 基本上是无操作的。 (呃,你又在这样做了。)
  • 等等。 preg_quote() 应该做什么?我认为您最终会得到如下所示的匹配模式:/^.*555AAAPPP \/\/ This line contain AAA line1 of FILE1 (remove).*$/ 将这些 cmets 从 FILE2 中取出并放弃 preg_quote 调用。

标签: php


【解决方案1】:

这行得通:

var_dump( CheckForMatches::run( "FILE1", "FILE2" ) );

class CheckForMatches
{
    private static $arrayBasePatterns;
    private static $arrayScanFile;

    public static function run( $baseFile, $targetFile )
    {
        self::$arrayBasePatterns = file( $baseFile,   FILE_IGNORE_NEW_LINES );
        self::$arrayScanFile     = file( $targetFile, FILE_IGNORE_NEW_LINES );

        $cleanedResult = array_filter( self::$arrayScanFile, 
                                       "CheckForMatches::arrayCallback" );
        return $cleanedResult;
    }

    public static function arrayCallback( $arrayElement )
    {
        foreach ( self::$arrayBasePatterns as $basePattern )
        {
            if ( strpos( $arrayElement, $basePattern ) !== FALSE )
            {
                return FALSE;
            }
        }
        return TRUE;
    }
}

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多