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:

  1. first replace duplicate whitespaces single one.

    $text = preg_replace( '/\s+/', ' ',$text ); 
  2. replace linebreaks 2 whitespaces.

    $text = str_replace( array( '\r', '\r\n', '\n'), '  ', $text ); 
  3. run functions..

  4. 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:

  1. $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.

  2. $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.

  3. $text = str_replace(' ', "\n", $text);

    once again, have use double quotes here, otherwise, end literal \n in place of double spaces.

ideone demo


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -