Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Fake good sorting for en-US
<?php
/*
* In 2013, locale-based sort is still broken or headache-inducing on many machines, and
* POSIX or C locales are the unassailable default in a shocking number of places. (For a
* fun exercise, try relying on LC_COLLATE for sorting in OS X.)
*
* This is a shameful PHP-based hack that mimics proper sorting for English using iconv
* transliteration. If doing things the WRONG WAY offends you, avert your eyes. However,
* this has worked for me in a pinch when I don’t have time to track down a box that has
* its i18n together.
*
* Short version: Sort correctly with “special characters.”
*/
# Set default form values:
$input = '';
$output = '';
# If form was posted, sort input:
if ( isset ( $_POST['text'] ) && trim ( $_POST['text'] ) ):
$text = explode ( "\n", trim ( $_POST['text'] ) );
$sort = array_map ( 'transliterate', $text );
asort ( $sort );
foreach ( $sort as $line_number => $line ):
$sort [ $line_number ] = $text [ $line_number ];
endforeach;
$input = trim ( implode ( "\n", $text ) );
$output = trim ( implode ( "\n", $sort ) );
endif;
function transliterate ( $string )
{
return
strtolower (
preg_replace ( '/[^-\w\t]+/', '',
str_replace ( ', ', "\t",
iconv ( 'UTF-8', 'ASCII//TRANSLIT',
trim ( $string )
)
)
)
);
}
?>
<form name="sort" method="POST" action="">
<fieldset id="TextFields">
<textarea name="text"><?php echo ( $input ); ?></textarea>
<input type="submit" id="Sort" value="Sort">
</fieldset>
<?php if ( $output ): ?>
<fieldset id="OutputFields">
<label for="Output">Sorted text</label>
<textarea name="Output" id="Output" wrap="hard"><?php echo ( $output ); ?></textarea>
</fieldset>
<?php endif; ?>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment