使用PHP's sort来排除标题开头的某些单词


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

简单的问题,排除专辑标题开头的'a'和'the'这样的单词,以便更好地按字母顺序对标题数组进行排序的最佳方法是什么?我有一个功能,但它似乎有点俗气,我想知道是否有一个更好的方法来做到这一点(我肯定有),我没有想到。

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']);
}

如前所述,这工作得很好,只是它似乎不是一个很好的方法。什么好主意吗?

你可以使用preg_replace来简化你的代码:

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'])
    );
}

另一种方法是将循环展开到if/elseif块中。(这看起来更快)

无论你想出什么方法,一定要测试它们(在10,000个专辑标题上运行10次),看看哪一个最快。那就用那个吧!

在比较之前使用regex应该可以工作:

// 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']) );
}

这样可以在比较之前对字符串执行其他调整。
这里找到preg_replace文档,这里找到regex信息