Reputation: 3823
$city = 'London Paris Lisabona';
And i need print this string in textarea. How print city in new line? I need in textarea get this:
London
Paris
Lisabona
Code:
$city = 'London\nParis\nLisabona';
echo '<textarea>'.$city.'</textarea>';
result:
London\nParis\nLisabona
Upvotes: 0
Views: 552
Reputation:
works in <textarea>
form me, lines might get soft-wrapped though (but that is expected)
Upvotes: 0
Reputation: 161
If you want "\n" to be converted to line breaks, you need to use double-quotes instead of single quotes.
i.e.
$foo = 'a\nb\nc\n';
echo $foo;
> a\nb\nc\n
$foo = "a\nb\nc\n";
echo $foo;
> a
> b
> c
Upvotes: 0
Reputation: 817238
In general: Use \n
for line breaks.
In your case (only works of cites don't consist of two words, i.e. each word must be a city):
$city = str_replace(' ',"\n", $str); // generates 'London\nParis\nLisabona'
Or if possible build the string with \n
instead of spaces from the beginning.
Update:
Escaped character sequences like \n
are only processed in double quoted strings. They are taken literally in single quoted strings (with two exceptions). Read more in the documentation:
To specify a literal single quote, escape it with a backslash (
\
). To specify a literal backslash, double it (\\
). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as\r
or\n
, will be output literally as specified rather than having any special meaning.
Thus, you have to declare your strings as
$cities = "London\nParis\nLisabona";
Further note:
Whenever possible avoid echoing HTML with PHP. It makes it more difficult to debug the HTML. Instead, embed the PHP into HTML like so:
<?php
$cities = "London\nParis\nLisabona";
?>
<textarea><?php echo $cities; ?></textarea>
Upvotes: 5
Reputation: 19380
$city = str_replace(' ', "<br />", $city);
If you echo it in HTML.
Upvotes: 1
Reputation: 763
<?php
$city = "London\nParis\nLisabona";
?>
<textarea rows="3" cols="20">
<?php echo $city; ?>
</textarea>
Upvotes: 2