Handling new lines in php

删除回忆录丶 提交于 2019-12-20 02:15:48

问题


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.


回答1:


I'd suggest you skip the nl2br until you're ready to actually send the data to the client. To tackle your problem:

// $string = $get->data->somehow();
$array = preg_split('/\n|\r\n/', $string);



回答2:


When you receive the input in your script normalize the end-of-line characters to PHP_EOL before storing the data in the data base. This tested out correctly for me. It's just one more step in the "filter input" process. You may find other EOL character strings, but these are the most common.

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

Explode on PHP_EOL and skip the nol2br() part. You can use var_dump() to see the resulting array.



来源:https://stackoverflow.com/questions/14113419/handling-new-lines-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!