php gets the value of textarea and handles carriage return and line feed

  • 2021-07-22 09:06:22
  • OfStack

This article illustrates how php gets the value of textarea and processes carriage return and line feed. Share it for your reference. The specific implementation method is as follows:

Generally speaking, in the html form, in textarea, we press carriage return and line feed, which are coded by ascii or special characters. If you don't convert the output text, it won't be typeset.

php to get the value of textarea is a simple textarea carriage return behavior\ r\ n Let's see the example below
HTML code:

<Textarea name="test" rows="3 "  cols="20 "  id="test"></textarea>

PHP code:

$str=$_GET['test'];
echo $str.'<br />';
$arr=explode("\n",$str);
print_r($arr);
echo count($arr).'<br />';// Number of carriage returns
$str1=nl2br($str);// Enter for line break
echo $str1;

All codes:

<html>
<head>
<title></title>
</head>
<body>
<form action="">
<textarea name="test"></textarea>
<input type="submit"  />
</form>
<?php
$str=$_GET['test'];
echo $str.'<br />';
$arr=explode("\n",$str);
print_r($arr);
echo count($arr).'<br />';// Number of carriage returns
$str1=nl2br($str);// Enter to line feed default function
echo $str1;
?>
</body>
</html>

Let's look at an example in dz forum. Not much to say, directly on the code:

$names = preg_split('/\r\n/',$_POST['textarea']);
foreach($names as $name){
    // todo something eg: echo $name;
}

The value is very simple, then the assignment, in textarea output line break is not so simple

$vals = get_from_mydb();
$tmp = '';
foreach($vals as $val){
    $tmp .= $val.'&#13;&#10;';
}

" & # 13; "And" & # 10; What do you mean "
I believe everyone has seen that in fact, the carriage return in textarea becomes "\ n", so php processing carriage return in textarea is actually processing "\ n" in characters.

I hope this article is helpful to everyone's PHP programming.


Related articles: