1

I have a text area that allows the user to input multiple lines of text. I would like to force everything in the text box to automatically be double spaced. I am using nl2br to output text and show the spacing.

Lets say the user types:

red
blue
green

I would like the nl2br function to output

red

blue

green

I would also need to be able to handle double spaces (i.e. if the user already puts in double spacing, I don't want more.

Any ideas on how to produce this? I would rather do it in the page that allows the user to enter the text if possible. Thanks!

HamZa
  • 14,671
  • 11
  • 54
  • 75
Brandon
  • 2,163
  • 6
  • 40
  • 64

3 Answers3

3

Using str_replace() and PHP_EOL:

$str = 'red
blue
green';

$str = str_replace(PHP_EOL, '<br><br>', $str);
echo $str;

EDIT: Using regex:

$str = 'red

blue



green
blue';

$str = preg_replace(array('/(\r?\n)+/', '/\r?\n/'),array(PHP_EOL,'<br><br>'), $str);
echo $str;
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • 1
    thanks - need to update my question to ask if this will handle double spaces (i.e. if the user already puts in double spacing, I don't want more.) – Brandon Mar 19 '13 at 10:32
  • you duplicated `\r?` I think you need it also for `\n?` –  Mar 19 '13 at 10:43
  • @Akam if you use `\r?\n?` this will match everything. – HamZa Mar 19 '13 at 10:44
  • @HamZaDzCyberDeV: look at `array('/(\r?\n)+/', '/\r?\n/')` why `\r?` duplicated? –  Mar 19 '13 at 10:51
  • @Akam What i wanted to do is to make it work on both Linux and Windows. [To explain things out](http://en.wikipedia.org/wiki/Newline): Linux uses `\n` and Windows uses `\r\n`. The first `/(\r?\n)+/` will replace all new lines (double or triple lines, or more ...) with one new line `PHP_EOL` then we replace ALL `PHP_EOL` which you may match with `/\r?\n/` with double br's `

    `. I hope i made it clear.
    – HamZa Mar 19 '13 at 10:57
0
$str = nl2br(str_replace(PHP_EOL, '<br><br>', $str));
echo $str;
Kautil
  • 1,321
  • 9
  • 13
  • There's no reason to wrap it in `nl2br()` anymore. There are no newlines left after `str_replace()` has removed them. – JJJ Mar 19 '13 at 10:51
0
$str = str_replace('<br />', '<br /><br />', nl2br($str));

This will make <br /> tags out of all line endings and afterwards double them.

Xavjer
  • 8,838
  • 2
  • 22
  • 42