animuson
animuson

Reputation: 54729

Using PHP's usort to exclude certain words at the beginning of the title

Simple question, what's the best way to exclude words such as 'a' and 'the' at the beginning of an album title to better sort your array of titles alphabetically. I have a function that works but it seems to be kind of tacky, I was wondering if there is a better way to do it than this (I'm sure there is) that I'm not thinking of.

function cmp($a, $b) {
    $excludes = array('a', 'the'); // Add excluded words here
    foreach ($excludes as $word):
        if (strtolower(substr($a['title'], 0, strlen($word) + 1)) == "{$word} ") $a['title'] = substr($a['title'], strlen($word) + 1);
        if (strtolower(substr($b['title'], 0, strlen($word) + 1)) == "{$word} ") $b['title'] = substr($b['title'], strlen($word) + 1);
    endforeach;
    return strcasecmp($a['title'], $b['title']);
}

As stated, this works perfectly fine, it just doesn't seem to be a very good way of doing it. Any ideas?

Upvotes: 0

Views: 466

Answers (3)

knittl
knittl

Reputation: 265251

you could use preg_replace to simplify your code a bit:

function cmp($a, $b) {
    static $excludes = '/^(an?|the)\s+/i'; // Add excluded words here
    return strcasecmp(
      preg_replace($excludes, '', $a['title']),
      preg_replace($excludes, '', $b['title'])
    );
}

Upvotes: 2

CaNNaDaRk
CaNNaDaRk

Reputation: 1322

Using regex just before compare should work:

// Adjust song title deleting "the" or "a" and trimming left spaces
function adjust( $title ) {
   return preg_replace( "/^(the|a) */i", "");
}
function cmp($a, $b) {
    return strcasecmp( adjust($a['title']), adjust($b['title']) );
}

This way you can perform also other adjustments on strings before compare.
Here you find preg_replace doc, and here you find regex infos

Upvotes: 0

helloandre
helloandre

Reputation: 10721

Another way is to unroll your loop into if/elseif blocks. (which would seem faster IMHO)

Whichever methods you come up with, be sure to test them (run them on 10,000 album titles 10 times) and see which one is fastest. Then use that one!

Upvotes: 0

Related Questions