Liam Bailey
Liam Bailey

Reputation: 5905

Removing whitespace

I am writing html content to a BML file, how can I remove new lines/whitespace so it is all in one long string?

does preg_replace("\n","") work?

Upvotes: 1

Views: 336

Answers (5)

Thomas Havlik
Thomas Havlik

Reputation: 1388

I would replace all \n with a space, then replace double spaces with a single space (being as HTML does not use more than one space by default)

$str = str_replace('\n', ' ', $str);
$str = str_replace('  ', ' ', $str);

Upvotes: 0

Otar
Otar

Reputation: 2591

Better use platform independent ending line constant PHP_EOL which is equivalent to array("\n", "\r", "\r\n") in this case...

$html = str_replace(PHP_EOL, null, $html);

Upvotes: 3

Marius Schulz
Marius Schulz

Reputation: 16440

The preg_match method does not work in this case as it does not replace characters but tries to find matches.

Upvotes: 0

Hannes
Hannes

Reputation: 8237

preg_match only compares and returns matches, it does not replace anything, you could use $string = str_replace(array(" ","\n"),"",$string)

Upvotes: 2

VoteyDisciple
VoteyDisciple

Reputation: 37803

If you just want to remove newline characters, str_replace is all you need:

$str = str_replace("\n", '', $str);

Upvotes: 1

Related Questions