php去除空行
要去除PHP中的空行,您可以使用以下方法之一:
- 使用
preg_replace函数:该函数可以使用正则表达式来匹配并替换字符串。
// 从字符串中去除空行
$noEmptyLines = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $yourString);
// 从文件中去除空行
$fileContent = file_get_contents($filePath);
$noEmptyLines = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $fileContent);
file_put_contents($filePath, $noEmptyLines);
- 使用
str_replace函数:该函数可以简单地替换字符串。
// 从字符串中去除空行
$noEmptyLines = str_replace(array("\r\n", "\r", "\n"), '', $yourString);
// 从文件中去除空行
$fileContent = file_get_contents($filePath);
$noEmptyLines = str_replace(array("\r\n", "\r", "\n"), '', $fileContent);
file_put_contents($filePath, $noEmptyLines);
请注意,这些方法都会将所有连续的空行替换为一个空行。如果您希望完全删除所有空行,请将替换字符串设置为空字符串''
原文地址: https://www.cveoy.top/t/topic/iEGk 著作权归作者所有。请勿转载和采集!