简体   繁体   中英

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

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);

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, ie "\\n" or else a carriage return followed by a newline, ie "\\r\\n".

Incidentally, all data submitted via a POSTed form (as well as a GET) should be considered tainted until validated or filtered, ie 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'] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM