BitValentine
BitValentine

Reputation: 78

I need the Textarea to output as carriage returns as \r in a string [PHP]

I've been hitting my head trying to output my text area to a string which includes carriage returns as \r in a string.

No, I don't want nl2br, I need the physical string.

Text area text example:

All I want is a 
carriage return
to look like this

And to output when processed in a form in PHP to look like this

echo $_POST['text area'];

The string needs to output like this

All I want is a \rcarriage return \rto look like this

I've looked online and all over stackoverflow and cannot find the answer that works.

Thanks in advance

Upvotes: 0

Views: 610

Answers (2)

slevy1
slevy1

Reputation: 3820

If you wish to have a string that is capable of displaying over multiple lines and you want to have it contain a carriage return, then what is actually needed are lines terminating with a carriage return followed by a newline, the way the end of line is expressed in a Windows environment.

Here's an example:

<?php
$textarea = <<< HDOC
All I want is a 
carriage return
to look like this
HDOC;

$char = "";
$ascii = ord(PHP_EOL);

if ($ascii == 10) {
     $char = "\\n";
     $replaced = str_replace($char,"\\r".$char,$textarea);
     echo $replaced;
}

See live code

I use two slashes in the code so that PHP understands that I refer to the carriage return character itself, which is composed of a slash and the letter r. Without the extra slash, PHP would not recognized the slash mark but would instead try to generate a carriage return.

Per the PHP 7 source code in main, specifically in php.h, the end of line symbol refers either to a newline, i.e. "\n" or else a carriage return followed by a newline, i.e. "\r\n".

Incidentally, all data submitted via a POSTed form (as well as a GET) should be considered tainted until validated or filtered, i.e. at minimum you need to do something like this to avoid potential problems, such as cross-site scripting (XSS).

<?php echo htmlentities( $_POST['text area'] );

Upvotes: 1

ishegg
ishegg

Reputation: 9957

If you mean literally \r, then use str_replace() and put the second argument in single quotes:

<?php
$string = "All I want is a 
carriage return
to look like this";
echo str_replace("
", '\r', $string);

Demo

Otherwise, use double quotes (you'll get the actual new line character)

echo str_replace("
", "\r", $string);

Upvotes: 1

Related Questions