phpsortingtextareaconceptlexicographic-ordering

Preserve Line Breaks During Sort


This isn't necessarily PHP-specific, although I'm using PHP. I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

Cookie

Apple

Banana

I want to sort() these terms and display them after page submit, so that the results look like:

Apple

Banana

Cookie

and not like

Apple
Banana
Cookie

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear. The list in the textarea is entered by a user so it may or may not already contain extra newlines.


Solution

  • If there are always two newlines, then it's as easy as splitting, sorting and joining:

    $result = explode("\n\n", $text);
    sort($result);
    $result = implode("\n\n", $result);
    

    If it could be one or more newlines then:

    preg_match_all("/^(.+$)(\n+)?/m", $text, $matches);
    
    sort($matches[1]);
    
    $result = '';
    foreach($matches[1] as $key => $val) {
        $result .= $val . $matches[2][$key];
    }