开发者

PHP Textarea append

开发者 https://www.devze.com 2023-01-28 18:55 出处:网络
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.

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?


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.


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;


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

$_POST['textarea'] = '['.preg_replace('!((?:\n|\r)+)!', "]$1[", trim($_POST['textarea'])).']';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号