How can I remove blank lines from text in PHP?

Member

madalyn

by madalyn , in category: PHP , a month ago

How can I remove blank lines from text in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elwin_wilderman , a month ago

@madalyn You can try explode text by newline to array and then use array_filter to remove all empty elements from array and then implode it back, example in PHP:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php

$string = <<<EOT
First line

Second line

Third line
EOT;

// Explode text to array by newline
$string = explode("\n", $string);

// Applying array_filter to remove empty elements
$string = array_filter($string);

// Generate a new string back
$string = implode("\n", $string);

echo $string;