开发者

Can't see new lines on textarea - what could the problem be?

开发者 https://www.devze.com 2023-01-15 05:46 出处:网络
I have a php string w开发者_Python百科ith a lot of information to be displayed inside a textarea html element.

I have a php string w开发者_Python百科ith a lot of information to be displayed inside a textarea html element.

I don't have access to that textarea nor to the script (if any) that generates it.

$somestring = 'first line \nSecond line \nThird line.';

$somestring as NOT been "worked" with trim or filter_var. Nothing.

On the textfield, I get the \n printed on the textarea hence, not interpreted.

What can I try in order to have those new lines applied?

Thanks in advance.


Try wrapping $somestring with " (double quotes) instead of ' (single quotes)


\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.

Example:

<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+

Read more about this behaviour in the PHP manual


EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.

For instance, if you would have a string with a lot of new lines, you would use double quotes:

echo "This\nstring\nhas\na\nlot\nof\nlines\n";

But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:

echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string

echo '/regular expression/'; // Best way to write a regular expression


$somestring = "first line \nSecond line \nThird line.";

http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号