0

I'm trying to write a code which removes all white spaces but keeps paragraphs instead.

I have this code:

$replaced = preg_replace('/\s\s+/', ' ', "1st.     line
2nd.      line goes here

3rd. line   goes   there");

echo $replaced;

As an output I get:

1st. line 2nd. line goes here 3rd. line goes there

But it should be like this:

1st. line 
2nd. line goes here 

3rd. line goes there

nl2br() function isn't a good solution for me, because I need to put this output in a textarea.

user2534787
  • 115
  • 1
  • 7
  • Do you get that output in a browser or on CLI? If in browser view the source or place the output in `
    ` or a textarea as needed. Browsers won't show `\n` as linebreaks on a page
    – brombeer Oct 11 '21 at 05:57
  • I getting that output in browser and I'd like to get the same output in a browser with line breaks. – user2534787 Oct 11 '21 at 06:10

2 Answers2

0

Browsers will not show \n as linebreaks on a page. Either view the source of the page to make sure the output is as desired or place your output inside <pre></pre> or <textarea></textarea>:

$replaced = preg_replace('/\s\s+/', ' ', "1st.     line
2nd.      line goes here

3rd. line   goes   there");

echo "<textarea>{$replaced}</textarea>";
brombeer
  • 8,716
  • 5
  • 21
  • 27
0

/[\\t\' \']+/ this will remove tabs and spaces