插件窝 干货文章 php让fgets函数不获取换行符的方法有哪些

php让fgets函数不获取换行符的方法有哪些

换行符 line file 函数 484    来源:    2025-03-18

在PHP中,fgets函数用于从文件指针中读取一行数据,默认情况下它会包含换行符。如果你希望去除换行符,可以使用以下几种方法:

方法1:使用rtrim函数

rtrim函数可以去除字符串末尾的空白字符(包括换行符)。

$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = rtrim($line, "\r\n"); // 去除换行符
        echo $line;
    }
    fclose($file);
}

方法2:使用trim函数

trim函数可以去除字符串两端的空白字符(包括换行符)。

$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = trim($line); // 去除换行符和两端的空白字符
        echo $line;
    }
    fclose($file);
}

方法3:使用substr函数

如果你知道换行符的位置,可以使用substr函数来截取字符串。

$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = substr($line, 0, -1); // 去除最后一个字符(假设是换行符)
        echo $line;
    }
    fclose($file);
}

方法4:使用preg_replace函数

preg_replace函数可以通过正则表达式去除换行符。

$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = preg_replace("/\r|\n/", "", $line); // 去除换行符
        echo $line;
    }
    fclose($file);
}

方法5:使用str_replace函数

str_replace函数可以替换字符串中的换行符。

$file = fopen("example.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = str_replace(["\r", "\n"], "", $line); // 去除换行符
        echo $line;
    }
    fclose($file);
}

方法6:使用stream_get_line函数

stream_get_line函数可以读取一行数据,并且可以指定结束符。

$file = fopen("example.txt", "r");
if ($file) {
    while (($line = stream_get_line($file, 1024, "\n")) !== false) {
        echo $line;
    }
    fclose($file);
}

总结

以上方法都可以有效地去除fgets读取的字符串中的换行符。选择哪种方法取决于你的具体需求和代码风格。通常情况下,rtrimtrim是最常用的方法。