<?php
/*
Alphabetizes the content of a textarea on a line-by-line basis.
Sorting is case-insensitive.
Blank lines are removed.
One form button for forward sorting, another for reverse sorting.
*/
if (isset($_POST['content'])) // alphabetize everything
{
// break the text area into lines
$lines = explode("\n", $_POST['content']);
// now remove blank lines
function strip_blanks($val) {return trim($val) == '' ? false : true;}
$lines = array_filter($lines,strip_blanks);
// now alphabetize the array. The array is passed as a reference,
// and sorting is done in-situ
natcasesort($lines);
// now see if we're reverse sorting
if ($_POST['rsort'])
$lines = array_reverse($lines,false);
// make the list display safe
$sorted = htmlentities(implode("\n",$lines));
}
else // initialize
{
$sorted = '';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Textarea Sorter</title>
</head>
<body>
<p>
Enter or paste a list of items. When you press the "sort" button,
the list will be sorted alphabetically. Case is ignored.
</p>
<form action="" method="post">
<textarea cols="64" rows="10" name="content"><?php echo $sorted; ?></textarea><br />
<input type="submit" name="sort" value="sort" />
<input type="submit" name="rsort" value="reverse sort" />
</form>
</body>
</html>