Silverfall05
Silverfall05

Reputation: 1127

How to remove unnecessary whitespaces from string, so there are no extra spaces in HTML

How to remove unnecessary whitespaces from string, so there are no extra spaces in HTML??

Im getting string from DB and for now I'm trying to do something like:

nl2br(trim(preg_replace('/(\r?\n){3,}/', '$1$1', $comment->text)));

But it keep displaying like that:

enter image description here

What I need is to get perfect:

enter image description here

How it is done?? Because I'm bad at regex :(

EDIT: $comment->text contains text from DB:

enter image description here

Upvotes: 4

Views: 897

Answers (4)

Moddasir
Moddasir

Reputation: 1449

Use simple CSS

p.a {
  white-space: nowrap;
}
<p class="a">
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>

Upvotes: 0

Carlos
Carlos

Reputation: 5072

This works fine and also avoids multiple <br> tags following each other:

$string = '12
23
3
4
5
6';

var_dump(implode("\n<br>\n", preg_split('/(\r?\n)+/', $string)));

var_dump(preg_replace('/(\r?\n)+/', "\n<br>\n", $string));

Output:

string(38) "12
<br>
23
<br>
3
<br>
4
<br>
5
<br>
6"

string(38) "12
<br>
23
<br>
3
<br>
4
<br>
5
<br>
6"

Upvotes: 0

Artas
Artas

Reputation: 262

preg_replace('/(\r)|(\n)/', '', $comment->text);

Output

"1 2"<br>"2 3"<br>"3"<br>"4"<br>"5"

Upvotes: 1

Kirk
Kirk

Reputation: 5077

You can just use this str_replace if you want to remove just spaces

$string = str_replace(' ', '', $string);

or if you want to remove all whitespeces use this

$string = preg_replace('/\s+/', '', $string);

Upvotes: 0

Related Questions