Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Simple way to replace or remove empty lines with str_replace

$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.

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

Thanks for teaching.

like image 531
Stephayne Avatar asked Jan 24 '26 13:01

Stephayne


2 Answers

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:

  • http://php.net/manual/en/function.preg-replace.php
  • http://php.net/manual/en/function.str-replace.php
like image 132
Lekensteyn Avatar answered Jan 27 '26 02:01

Lekensteyn


str_replace can be passed an array as:

$line_out = str_replace(array("\r","\n"), '', $line_in);
like image 35
codaddict Avatar answered Jan 27 '26 02:01

codaddict