我想从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行不包含在一个完整的行中!
以下示例:
FILE1:
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
代码必须让代码保持原样,只需删除行。
答案 0 :(得分: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;
}
}