如何在 PHP 中比较两个具有不同行结尾的文本文件?
我需要在 php.ini 中比较两个文本文件。一个文件是用户上传的,另一个文件是由服务器提供的,在 Windows 上运行。 当文件从另一台 Windows 计算机提交时,这工作正常,但从 Linux 计算机提交文件时,文件会有所不同,我假设这是因为不同的行结尾。有没有一种简单的方法来比较 Windows 文本文件和 Linux 文本文件?
目前这是我的代码;
$text1 = file_get_contents($file1);
$text2 = file_get_contents($file2);
if (strcmp($content, $content2) == 0) { etc;
I need to compare two text files in php. One file is user uploaded, and the other is supplied by the server, running on windows.
This works fine when the file is submitted from another windows computer, but from a linux computer the files come out different, I am assuming this is because of different line endings. Is there an easy way to compare windows text files to linux text files?
Currently this is my code;
$text1 = file_get_contents($file1);
$text2 = file_get_contents($file2);
if (strcmp($content, $content2) == 0) { etc;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在两个文件中将
CRLF
行结尾替换为LF
行结尾,或者以其他方式替换 - 尝试如下操作:对于
$text2
也是如此>。You could replace
CRLF
line endings withLF
line endings or the other way around in both files - try something like this:And the same for
$text2
.只是为了添加另一个可能更便携的选项(其他回答者建议的替换已经适合您的情况),
file()
函数将文件数据分割成一个数组,似乎能够处理 Windows 和 Linux 编码:它还可以处理 Macintosh 行如果
auto_detect_line_endings< /code>
运行时设置已打开。
Just to add another, potentially more portable option (the replacing suggested by the other answerers will already fine for your the case), the
file()
function splits file data into an array and seems to be able to handle both Windows and Linux encodings:It can also deal with Macintosh line endings if the
auto_detect_line_endings
runtime setting is turned on.