Home

Library of Congress Call Number Sort in PHP

by Tomasz Neugebauer
tomasz.neugebauer@concordia.ca

Last update: August 12, 2008

I needed a function that will compare Library of Congress call numbers. I found a function in PERL to do this on Joshua McGee's site, but I needed it in PHP and our call numbers use a space instead of a period for some of the separators, for example: HA 1107 K49 2003.
Here is the function in PHP:

<?php //is call number $a larger than call number $b? function locsort ($a,$b) { $pattern ='/^([A-Z]+)\s?(\d+(?:\.\d+)?)\s?([A-Z]*)(\d*)\.?([A-Z]*)(\d*)( (?:\d{4})?)?(.*)?/'; $i = preg_match($pattern, $a, $regsA); $j = preg_match($pattern, $b, $regsB); if (($i==0)||($j==0)) { return($a > $b); } else { //if first part greater then return that //if first part equal, check second part, return that if ($regsA[1] != $regsB[1]){ return($regsA[1] > $regsB[1]); } else { if ($regsA[2] != $regsB[2]){ return ($regsA[2] > $regsB[2]); } else { if ($regsA[3] != $regsB[3]){ return ($regsA[3] > $regsB[3]); } else{ if ($regsA[4] != $regsB[4]){ return (("0.".$regsA[4]) > ("0.".$regsB[4])); } else { if ($regsA[5] != $regsB[5]){ return ($regsA[5] > $regsB[5]); } else { if ($regsA[6] != $regsB[6]){ return ($regsA[6] > $regsB[6]); } else { if ($regsA[7] != $regsB[7]){ return ($regsA[7] > $regsB[7]); } else { return ($regsA[8] > $regsB[8]); } } } } } } } } }