Reliably Remove Newlines From String

前端 未结 6 1163
忘了有多久
忘了有多久 2020-12-21 06:52

The string input comes from textarea where users are supposed to enter every single item on a new line.

When processing the form, it is easy to explode the textarea

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 07:11

    You can use preg_split to do that.

    $arr = preg_split('/[\r\n]+/', $textareaInput);
    

    It splits it on any combination of the \r or \n characters. You can also use \s to include any white-space char.

    Edit
    It occurred to me, that while the previous code works fine, it also removes empty lines. If you want to preserve the empty lines, you may want to try this instead:

    $arr = preg_split('/(\r\n|[\r\n])/', $textareaInput);
    

    It basically starts by looking for the Windows version \r\n, and if that fails it looks for either the old Mac version \r or the Unix version \n.

    For example:

    
    

    Prints:

    Array
    (
        [0] => Windows
        [1] => 
        [2] => Mac
        [3] => 
        [4] => Unix
        [5] => 
        [6] => Done!
    )
    

提交回复
热议问题