3

I have form in html where user can put the text in text area.
I save the content of text area into MySQL database (in field of type TEXT).
Then I somewhere in my aplication I need load that text and put it into array where in each index will be one line of the text.

<textarea rows="10" cols="80">
Row one
Row two
Row tree
</textarea>

array (output in "php pseudocode"):
$array = array();
$array[0] = Row one;
$array[1] = Row two;
$array[2] = Row tree;

How I do it: I save it to db then I load it and use:

$br = nl2br($string,true);
$array = explode("<br />", $br);

The reason why I use nl2br is I want to avoid problems with end of lines of the text from different platforms. I mean /n or /r/n.
But in my solution must be an error somewhere cause it doesn't work (an array $array is empty).

Better solution would be probably somehow split it into array using explode or something like that with pattern for line breaks but here is again the problem from beginning with line breaks which I don't know how to solve (problems with \n or \r\n).

Can anybody give me an advice? Thanks.

4

2 回答 2

4

我建议您跳过,nl2br直到您准备好将数据实际发送给客户端。要解决您的问题:

// $string = $get->data->somehow();
$array = preg_split('/\n|\r\n/', $string);
于 2013-01-01T19:25:49.827 回答
-1

当您在脚本中收到输入时,在将数据存储到数据库之前将行尾字符规范化为 PHP_EOL。这对我来说是正确的。这只是“过滤输入”过程中的又一步。您可能会发现其他 EOL 字符串,但这些是最常见的。

<?php // RAY_temp_user109.php
error_reporting(E_ALL);

if (!empty($_POST['t']))
{
    // NORMALIZE THE END-OF-LINE CHARACTERS
    $t = str_replace("\r\n", PHP_EOL, $_POST['t']);
    $t = str_replace("\r",   PHP_EOL, $t);
    $t = str_replace("\n",   PHP_EOL, $t);
    $a = explode(PHP_EOL, $t);
    print_r($a);
}

$form = <<<FORM
<form method="post">
<textarea name="t"></textarea>
<input type="submit" />
</form>
FORM;

echo $form;

在 PHP_EOL 上展开并跳过 nol2br() 部分。您可以使用 var_dump() 查看生成的数组。

于 2013-01-01T19:21:30.333 回答