Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spaces doesn't come after nl2br(htmlentities($text))?

Tags:

php

I am printing a article with spaces inside the article. Text inside article has HTML tags also,so i am using htmlentities before echo.

But problem is that display does't show spaces on the browser. What is the problem with these commands?

Can someone please suggest me a better option?

DB update command:

 mysql_real_escape_string($text, $db)

Article display command:

echo nl2br(htmlentities($row_page['text']));

Example: displayed text is pretty ugly

Real text and i am expecting same:

dbus-1/                   libcom_err.so.2@                     libglib-2.0.so.0@            liblvm2cmd.so.2.02*      libpopt.so.0.0.0*
device-mapper/            libcom_err.so.2.1*                   libglib-2.0.so.0.2200.5*     libm-2.12.so*            libproc-3.2.8.so*
firmware/                 libcrypt-2.12.so*                    libgmodule-2.0.so.0@   
like image 534
P K Avatar asked Feb 18 '26 15:02

P K


2 Answers

HTML collapses all whitespace (spaces or newlines or tabs) into a single space. You can work around it by replacing ' ' with '  ', for example:

echo str_replace('  ', '  ', nl2br(htmlentities($row_page['text'])));

But even cleaner is to just have the browser use pre formatted whitespace:

<pre><?php echo htmlentities($row_page['text']); ?></pre>

Or alternatively use CSS for a bit of extra flexibility:

<div style="white-space: pre;"><?php echo htmlentities($row_page['text']); ?></div>

Pre formatted whitespace has some drawbacks, for example you can't have any newlines or indentation in your HTML file when you're using pre, because the browser will render them. But when you really need to control how something is rendered it's the best choice.

like image 174
Abhi Beckert Avatar answered Feb 20 '26 04:02

Abhi Beckert


Browsers collapse continuous whitespace into a single space. That's the way it works, mainly so you can write source code like this:

<p>
    Some very long text nicely indented and readable in source,
    so it's easy to write for the author.
</p>

and it will display nicely in a browser like this:

Some very long text nicely indented and readable in source, so it's easy to write for the author.

To use pre-formatted text, wrap that section in a <pre> tag or use the equivalent CSS rule white-space: pre. The way you're escaping HTML makes this rather difficult of course. A markup language like Markdown may be the solution there.

like image 26
deceze Avatar answered Feb 20 '26 03:02

deceze