Removing whitespace
I am writing html content to a BML file, how can I 开发者_Python百科remove new lines/whitespace so it is all in one long string?
does preg_replace("\n","")
work?
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);
preg_match only compares and returns matches, it does not replace anything, you could use $string = str_replace(array(" ","\n"),"",$string)
If you just want to remove newline characters, str_replace
is all you need:
$str = str_replace("\n", '', $str);
The preg_match
method does not work in this case as it does not replace characters but tries to find matches.
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);
精彩评论