Last active
October 5, 2015 23:37
-
-
Save chriszarate/2896301 to your computer and use it in GitHub Desktop.
Fake good sorting for en-US
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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