我正在尝试匹配文件中的信息,但当我尝试使用preg_match("/^[1-9][0-9]{4}$/")
对其进行正则表达式时,我可以匹配单行,但在直接读取文件时无法匹配。我的代码如下:
<?php
$line = "23146";
$line = str_replace("n", "", $line);
if(preg_match("/^[1-9][0-9]{4}$/", $line, $matches)) { // Matching the PO No.
print_r($matches);
}
// Following don't work on PHP 5.3.26
$file = fopen("meaw.txt", "r") or die("Unable to open file");
while(!feof($file)) {
$line = fgets($file);
if(preg_match("/^[1-9][0-9]{4}$/", $line, $matches)) { // Matching the PO No.
print_r($matches);
}
}
fclose($file);
echo "nFile Closed";
?>
我的文件是这个meaw.txt
我的问题是,当我在ubuntu PHP7上运行该代码时,该代码可以工作。但当我在windows2008 php5.3.26上运行此代码时,它会打印以下
数组([0]=>23146)
文件关闭
但我应该得到
数组([0]=>23146)阵列([0]=>63144)阵列([0]=>63140)阵列([0]=>63201)阵列([0]=>63148)阵列([0]=>63201)阵列([0]=>63148)阵列([0]=>63201)阵列([0]=>63148)阵列([0]=>63201)阵列([0]=>63140)阵列([0]=>63148)
文件关闭
有人能告诉我为什么会发生这种情况吗?非常感谢。
问题是Windows将新行读取为"\r\n">,但unix读取方式不同。我所要做的就是在while循环中添加以下内容
$line = str_replace("rn", "", $line);