php - Replace all linebreaks with two whitespaces and revert it -
i'm trying temporarily replace linebreaks 2 whitespaces , after function on string revert 2 whitespaces linebreak.
but doesn't work. won't restore linebreaks.
this do:
first replace duplicate whitespaces single one.
$text = preg_replace( '/\s+/', ' ',$text );
replace linebreaks 2 whitespaces.
$text = str_replace( array( '\r', '\r\n', '\n'), ' ', $text );
run functions..
restore linebreaks
$text = str_replace( ' ', '\n', $text );
as far can see replaces linebreaks single whitespace. not defined 2 of them. happens? using \s\s
doesn't change things.
tested things:
str_replace
(step 2) fails detect linebreaks after used preg_replace
replace duplicate whitespaces (step 1).
without step 1 works.
i suggest using those:
$text = preg_replace('/ +/', ' ', $text);
this replace spaces.
\s
match more spaces, because matches vertical whitespaces linefeeds, carriage returns... , because of this, second replace wasn't having newlines replace.$text = str_replace(array("\r", "\r\n", "\n"), ' ', $text);
as hkpotter92 pointed out, need use double quotes, otherwise, trying match literal characters instead of carriable returns , of line feeds.
$text = str_replace(' ', "\n", $text);
once again, have use double quotes here, otherwise, end literal
\n
in place of double spaces.
Comments
Post a Comment