PHP multiple new lines

前端 未结 4 1065
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 16:27

I\'m a little stuck. How do I remove multiple newlines which are in a row with one newline. There could be anything up to 20 newlines next to each other. For example

相关标签:
4条回答
  • 2021-01-05 17:02
    $str = 'James said hello\n\n\n\n Test\n Test two\n\n';
    echo preg_replace('{(\\\n)\1+}','$1',$str);
    
    0 讨论(0)
  • 2021-01-05 17:09

    Try this one:

    $str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?";
    $str = preg_replace("/\n+/", "\n", $str);
    print($str);
    
    0 讨论(0)
  • 2021-01-05 17:17

    Improving on Marc B's answer:

    $fixed_text  = preg_replace("\n(\s*\n)+", "\n", $text_to_fix);
    

    Which should match an initial newline, then at least one of a group of any amount of whitespace followed by a newline and replace it all with a single newline.

    0 讨论(0)
  • 2021-01-05 17:21
    $fixed_text = preg_replace("\n+", "\n", $text_to_fix);
    

    This should do it, assuming that the consecutive newlines are truly consecutive and don't have any whitespace (tabs, spaces, carriage returns, etc...) between them.

    0 讨论(0)
提交回复
热议问题