首页 > 解决方案 > 比较两个 php 文件并删除匹配行

问题描述

好的,所以我有两个文件

a.php
b.php

我知道如何包含文件并显示 php 文件中的内容:

<?php include("https://www.example.com/a.php"); ?>

上面的代码完美运行。

我遇到的问题是,当我尝试比较两个 php 文件并删除匹配项时。

我有这个代码,但它不输出任何东西。一个空白。

<?php
$lines1 = include("https://www.example.com/a.php");
$lines2 = include("https://www.example.com/b.php");
$result = array_diff( $lines1, $lines2 );
print_r( $result );
?>

我试过这个:

<?php
$lines1 = include("https://www.example.com/a.php");
echo $lines1;
?>

即使上面的代码也不起作用。

编辑:

下面的代码确实有效(删除https://www.example.com/时):

<?php
$lines1 = include("a.php");
echo $lines1;
?>

两个 php 文件都不包含数组。

基本上两者都在新行中返回一个 url 列表,如下所示:

http://www.example.com/1

http://www.example.com/2

我想比较并且不显示匹配的行。

所以,假设 a.php 有:

苹果

香蕉

和 b.php 有:

香蕉

然后只会显示苹果。忽略比赛。

任何帮助,将不胜感激。

标签: phpinclude

解决方案


include函数实际上导入了包含文件中的PHP 代码,因此它成为文件中代码的一部分,并由 PHP 解释器评估(运行)。看起来您想使用file函数,它将文件的行读入数组。

正如@AbraCadaver 提到的,如果您从 URL 中包含,则需要启用 allow_url_fopen 。如果你不能这样做,你将需要使用 curl 或其他一些 HTTP 客户端。

然后,您需要一种从两个数组中获取不同条目的方法。array_diff实际上并没有这样做,它只返回第一个参数中不存在于其他任何参数中的条目。这不是要求,也没有内置的(我不这么认为)可以做到这一点,所以让我们自己动手吧。

<?php

$aFile = file('a.txt');
$bFile = file('b.txt');

/**
 * Return the entries that appear in either array, but not both
 * 
 * @param array $a
 * @param array $b
 * @return array
 */
function array_distinct(array $a, array $b)
{
    // Normalize line endings, etc
    $a = array_map('trim', $a);
    $b = array_map('trim', $b);

    // De-dup
    $a = array_unique($a);
    $b = array_unique($b);

    // Get the common items
    $common = array_intersect($a, $b);

    // Merge both arrays
    $all = array_merge($a, $b);

    // Filter out the common entries
    $output = array_diff($all, $common);

    // Re-key on the way out
    return array_values($output);
}

$distinctEntries = array_distinct($aFile, $bFile);

assert(sizeof($distinctEntries)==2, 'We should see two entries');
assert($distinctEntries[0] == 'http://www.example.com/3', 'Entry should match expectation');
assert($distinctEntries[1] == 'http://www.example.com/4', 'Entry should match expectation');

print_r($distinctEntries);

一个.txt:

http://www.example.com/1
http://www.example.com/2
http://www.example.com/3

b.txt:

http://www.example.com/1
http://www.example.com/2
http://www.example.com/4
http://www.example.com/4

推荐阅读