PHP 按行比较两个文本文件


PHP compare two text files by lines

我需要比较两种语言文件 - 英语和德语。每个文本文件每行有一个单词/短语。第一语言中的单词/短语 [x] 是第二语言中的单词/短语 [x]。翻译后的单词在第二个文件中的同一行上。

我尝试使用以下代码获取翻译,但似乎循环不起作用。我总是得到"没有"。有什么想法吗?

function translation($word,$service,$sprache1,$sprache2){
$typus ="transl";
$mypath = "data/".$service."/";
mkdir($mypath,0777,TRUE);
//fh - First language file
$myFile = $mypath."".$typus."-".$sprache1.".txt";
$fh = file($myFile) or die("can't open file");
//fh2 - Second language file
$myFile2 = $mypath."".$typus."-".$sprache2.".txt";
$fh2 = file($myFile2) or die("can't open file");

$x=0;
$result = "none";
foreach ($fh as $line) {

        if (stripos($word,$line))
        {$result = $fh2[$x];
        break;
        } 
$x=$x+1;
            }
return $result;                                                         
}                   

我认为你的问题出在错误的if陈述中。关键是stripos(如strpos)可以返回 0false

例如,如果您在单词"cats"中搜索"cat"stripos将返回 0,因为它是 cat-string 的第一个位置。另一方面,如果你在单词"cats"中搜索"狗"stripos将返回 false,因为什么也找不到。

因此,在您的函数中,if情况应该更加严格:

if (stripos($word,$line) !== false)

这意味着即使您的单词从位置 0 开始,也会找到它。您当前的if语句不允许接受 0(零)值。

测试您的代码后,我发现了 2 个不同的问题。

首先,小心条纹。如果在开头(即位置 0)找到$needle,则返回0,如果未找到$needle则返回false。在 PHP 中,默认情况下0被评估为false。您应该将if语句更改为:

if(stripos($word, $line) !== false)

请注意 !== 运算符,它比 != 强。

第二个也是最重要的问题,它阻止你的函数工作,是你比较可以包含不可见字符的行(例如"换行符"字符)。您应该在比较字符串之前修剪它们。我会将您的if语句更改为:

if(trim($word) === trim($line))

哪个更简单。或者如果你真的想保留stripos

if(stripos(trim($word), trim($line)) !== false)