Textarea to array or implode?

Let's say that I have a text area, the user enters the information in the same way as in the style below:

Ice cream
Chocolate

then sends this information, I want to get the information EXACTLY like this:

Ice cream, Chocolate

This is the best way to do this:

$arr = explode("\n", $var);
$arr = implode(",", $arr);

When doing this, it displays information like this:

Ice cream , Chocolate

Pay attention to the space after the cream, is it easy to trim()fix this?

+3
source share
4 answers
$text = preg_replace("~\s*[\r\n]+~", ', ', $text);
+7
source

Do not save the changed data in db, just save the original, so when you present it to the user, they can easily edit them.

As for displaying them when you present the output to the users browser, use the regex as indicated by zrekms above

$text = preg_replace("~\s*[\r\n]+~", ', ', $text);

.

, BTW , , , , ...

$arr = explode("\n", $var);
$arr = explode("\r\n", $var);
$arr = explode("\r", $var);

$arr = explode(PHP_EOL, $var);

PHP_EOL char .

+1

Just guessing, but will "\ r \ n" in the explosion fix the problem? I know that a new line has appeared on Windows computers.

0
source

You can use preg_split with regular expressions:

http://php.net/manual/en/function.preg-split.php

-2
source

Source: https://habr.com/ru/post/1784896/


All Articles