PHP A simple way to replace or remove blank lines with str_replace

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

This works for me, but somewhere I saw an example [\ n \ r] and I cannot find it.

I just want to get rid of empty lines. The above is in the foreach loop.

Thanks for the training.

+3
source share
3 answers

You should not use -in variable names;)

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

Manual entries:

+10
source

str_replace can pass an array as:

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

php.net # 2 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 first so they aren't converted twice.
$newstr = str_replace($order, '', $str);
0

Source: https://habr.com/ru/post/1766234/


All Articles