IRsoft - Software and more by Ingmar Runge

PHP: Longest common prefix

This function finds the longest common prefix from a list of strings.

<?php
 
// inspired by http://linux.seindal.dk/2005/09/09/longest-common-prefix-in-perl/
 
function longest_common_prefix(array $arr, $ignore_empty = false)
{
    $prefix = NULL;
    
    foreach($arr as $s)
    {
        if($ignore_empty && empty($s)) continue;
        
        if(is_null($prefix))
        {
            $prefix = $s;
        }
        else
        {
            while(!empty($prefix) && substr($s, 0, strlen($prefix)) != $prefix)
            {
                $prefix = substr($prefix, 0, -1);
            }
        }
    }
    
    return $prefix;
}
 
?>
Last edited by Ingmar on Tuesday, April 7th 2009 14:48:17 CEST