0

OK let's say I have a textarea and I type in that textarea

Hello my name is
Frank and I like
to eat apples.

then when I hit submit button I get:

[Hello my name is]
[Frank and I like]
[to eat apples.]

See how every line is appended at the start and end with brackets?

Is there a way you can even do this in PHP?

2
  • Are you saying that you want that behavior? Dec 2, 2010 at 18:20
  • I'm asking if it is possible to split up every line in a textarea and append it.
    – test
    Dec 2, 2010 at 18:22

3 Answers 3

6

Yes:

$output = '['.str_replace("\n", "]\n[", $input).']';

I'm not sure if a textarea sends \n or \r\n. If its the latter, just change \n to \r\n in the above.

0
3

Simplest (and fastest) way to do this is via a string replace. Assuming a "message" textarea:

$text = isset($_POST['message']) ? $_POST['message'] : '';
$text = str_replace("\n\r", "\n", $text);
$text = str_replace("\r", "\n", $text);
$text = "[" . str_replace("\n", "]\n[", $text) . "]";
echo $text;
1

If you want to preserve spacing then you have to use regular expressions:

$_POST['textarea'] = '['.preg_replace('!((?:\n|\r)+)!', "]$1[", trim($_POST['textarea'])).']';
3
  • my advice (always) is to munge raw input data into a known format, maybe call it a standard for your application. then, you can reformat it as appropriate for output requirements.
    – zanlok
    Dec 2, 2010 at 21:26
  • 1
    Not quite sure what that comment means? I just added a method that would preserve multiple newlines between lines with text rather than leaving blank lines with [] on them. I'm pretty certain that the output is no more or less a 'known format' in either case! str_replace is far faster if that's all that's needed though, I agree. Dec 2, 2010 at 21:50
  • I mean that software should have data integrity, including newline structure. Not saying preg isn't a good idea, but just explaining the reason for a data-cleaning approach.
    – zanlok
    Dec 2, 2010 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.