Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea into an array or implode?

Tags:

php

Say I have a text area, user enters information exactly like styled below:

Ice cream
Chocolate

then submits this information, I want to retrieve the information EXACTLY like so:

Ice cream, Chocolate

Is this the best way to do it:

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

When doing it like this, it puts the information out like so:

Ice cream , Chocolate

Note the space after cream, will a simple trim() fix this?

like image 660
Latox Avatar asked Nov 19 '25 22:11

Latox


2 Answers

$text = preg_replace("~\s*[\r\n]+~", ', ', $text);
like image 179
zerkms Avatar answered Nov 21 '25 14:11

zerkms


Dont store modified data in db, just store original one so when you present it to user they can edit them easily.

As far as displaying them, when you present output to users' browser use regex as mentioned by zrekms above

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

Above line is good enough.

Oh BTW for those who want to explode new line but dont know how because they are different on each OS, Instead of doing this...

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

Just use

$arr = explode(PHP_EOL, $var);

PHP_EOL is equivalent to new line char and its OS independent.

like image 20
Aamir Mahmood Avatar answered Nov 21 '25 13:11

Aamir Mahmood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!