Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

php - Reliably Remove Newlines From String

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 input into an array of single items like this:

$arr = explode("
", $textareaInput);

It works fine but I am worried about it not working correctly in different systems (I can currently only test in Windows). I know newlines are represented as or as just across different platforms. Will the above line of code also work correctly under Linux, Solaris, BSD or other OS?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use preg_split to do that.

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

It splits it on any combination of the or 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('/(
|[
])/', $textareaInput);

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

For example:

<?php
$text = "Windows

Mac

Unix

Done!";
$arr = preg_split('/(
|[
])/', $text);
print_r($arr);
?>

Prints:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...