【发布时间】: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