Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
800 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 Answer

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!
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...