NuSphere Forums Forum Index
NuSphere Forums
Reply to topic
/r Carriage Return not working


Joined: 23 Jul 2010
Posts: 3
Reply with quote
I've looked and looked-- and everything I read says that "\r" is supposed to generate a return. But it doesn't. I've tried everything I can think of.

I've been programming for 20 years. It feels silly to ask such a question. Though-- I'm just getting started with PHP.

Here's some sample code. Thanks

<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.\r";

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
View user's profileFind all posts by sozenSend private message


Joined: 23 Jul 2010
Posts: 3
Reply with quote
Using the HTML, <br /> instead of the "\r" seems to work--

so-- when do you use the "\r" for return or the "\n for new line?
View user's profileFind all posts by sozenSend private message


Joined: 06 Jul 2009
Posts: 72
Reply with quote
We all have to start somewhere with a new language Smile

The problem you have here isn't actually PHP related, but HTML.

Both \r and \n work as you'd expect in PHP itself, for example, from a console window, try:

Code:
php -r 'echo "This is line one\nThis is line 2\n";'


and you'll get:

Code:
This is line one
This is line 2


Same as if you run a PHP script a non-web environment.

HTML however, requires tags rather than escape codes, and that's why '<br />' works for you there rather than a \n or \r.

I assume you're running the code in a web environment, and although you're echoing data from PHP, it's actually being rendered by the HTML engine.

If you really want to use \r or \n in a web environment, you'll need to either wrap the 'echo' statement(s) in <pre></pre> tags, or define a text content type ( header('Content-type: text/plain'); ). Different situations / results that you're looking for would depend on what method was actually required, but if you're looking to generate HTML output, just continue with the '<br />' tag and all will be well Smile

Just FWIW.. PHP also comes with a 'nl2br()' function that will convert newline codes to '<br />' tags. Useful when reading plain text in to display as HTML (for example, a basic news article stored in a database with no HTML tags or parsing a plain text document etc).

HTH Smile



Regards,

Ian
View user's profileFind all posts by Ian.HSend private message
/r Carriage Return not working
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
All times are GMT - 5 Hours  
Page 1 of 1  

  
  
 Reply to topic