且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP-如何在数组中查找重复的值分组

更新时间:2022-12-12 13:53:44

字符数组只是字符串.正则表达式是字符串模式匹配之王.添加递归,即使从字符数组来回转换,解决方案也非常优雅:

Character arrays are just strings. Regex is the king of string pattern matching. Add recursion and the solution is pretty elegant, even with the conversion back and forth from character arrays:

function findPattern($str){
    $results = array();
    if(is_array($str)){
        $str = implode($str);
    }
    if(strlen($str) == 0){ //reached the end
        return $results;
    }
    if(preg_match_all('/^(.+)\1+(.*?)$/',$str,$matches)){ //pattern found
        $results[] = array('number' => (strlen($str) - strlen($matches[2][0])) / strlen($matches[1][0]), 'values' => str_split($matches[1][0]));
        return array_merge($results,findPattern($matches[2][0]));
    }
    //no pattern found
    $results[] = array('number' => 1, 'values' => array(substr($str, 0, 1)));
    return array_merge($results,findPattern(substr($str, 1)));
}

您可以在此处进行测试: https://eval.in/507818 https://eval.in/507815

You can test here : https://eval.in/507818 and https://eval.in/507815