Search code examples
phphtmlnl2br

Automatically Double Space Text Area


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!


Solution

  • 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;