First, I'd like to point out that new lines can be either
,
, or
depending on the operating system.
My solution:
echo preg_replace('/[ ]+/', ' ', preg_replace('/[
]+/', "
", $string));
Which could be separated into 2 lines if necessary:
$string = preg_replace('/[
]+/', "
", $string);
echo preg_replace('/[ ]+/', ' ', $string);
Update:
An even better solutions would be this one:
echo preg_replace('/[ ]+/', ' ', preg_replace('/s*$^s*/m', "
", $string));
Or:
$string = preg_replace('/s*$^s*/m', "
", $string);
echo preg_replace('/[ ]+/', ' ', $string);
I've changed the regular expression that makes multiple lines breaks into a single better. It uses the "m" modifier (which makes ^ and $ match the start and end of new lines) and removes any s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…