PHP 使用 str_replace 替换或删除空行的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3779464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:03:57  来源:igfitidea点击:

PHP Simple way to replace or remove empty lines with str_replace

phpstr-replace

提问by Stephayne

$line-out = str_replace('\r', '', str_replace('\n', '', $line-in));

The above works for me but, I saw a [\n\r] example somewhere and I cannot seem to find it.

以上对我有用,但是,我在某处看到了 [\n\r] 示例,但似乎找不到它。

I just want to get rid any blank lines. The above is in a foreach loop.

我只想摆脱任何空行。以上是在foreach循环中。

Thanks for teaching.

谢谢教导。

回答by Lekensteyn

You shouldn't use -in variable names ;)

你不应该-在变量名中使用;)

$line_out = preg_replace('/[\n\r]+/', '', $line_in);
$line_out = str_replace(array("\n", "\r"), '', $line_in);

Manual entries:

手动输入:

回答by codaddict

str_replacecan be passed an array as:

str_replace可以通过一个数组作为:

$line_out = str_replace(array("\r","\n"), '', $line_in);

回答by nush

This is from php.net's example #2 in str_replace(modified to suit the "environment"):

这是来自 php.net's example #2 in str_replace(修改以适应“环境”):

<?php
// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, '', $str);