Bas Smits
Bas Smits

Reputation: 11

how to print special characters which are a string in variable with php?

I'm making this chat server, but it doesn't work quite well. When you send a piece of text, it first gets encoded by the function base64_encode() and then gets sent to a MySQL database. Then the receiver gets the text from that same MySQL database, which is of course first decoded by the function base64_decode().

The only problem is with the special characters like \n \' and \t: when I get the data from the database and print it between two textarea tags, I see \n as a string, and not as actual line breaks.

In short, I need to fix this problem:

$String = 'Line 1 \n Line 2';
print '<textarea>' . $String . '</textarea>';

//The result I want
//<textarea> Line 1
//Line 2 </textarea>

The function nl2br doesn't work, because tags inside a textarea tag won't work, and also because there other characters like apostrophes.

Could anybody help me?

Thanks!

Upvotes: 1

Views: 1085

Answers (3)

Mahdi
Mahdi

Reputation: 9417

This one is also works same as using " ... ", however maybe helps in your case:

$string = <<<EOT
Line 1 \n Line 2
EOT;

echo '<textarea>' . $string . '</textarea>';

As the others said, your problem is Single-Quotes.

Upvotes: 0

robonerd
robonerd

Reputation: 198

You need to enclose your string into double quotes, for special characters to be evaluated.

$String = "Line 1 \n Line 2";
print '<textarea>' . $String . '</textarea>';

Upvotes: 1

rationalboss
rationalboss

Reputation: 5389

If you change this:

$String = 'Line 1 \n Line 2';
print '<textarea>' . $String . '</textarea>';

to this:

$String = "Line 1 \n Line 2"; // double quote
print '<textarea>' . $String . '</textarea>';

... you will get the output you want.

Upvotes: 0

Related Questions