Handling new lines in php

孤街醉人 提交于 2019-12-01 20:40:50

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

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.

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