Search code examples
phpstringrecursionautoloadstrrchr

Cut string by substrings after none left


I have a string Field-Text-Datepicker. I need to "explode" it to following array:

array(
    [0] => field-text-datepicker
    [1] => field-text
    [2] => field
);

I've tried some combinations of strrchr(), recursion and for loops, but everything I've made seem to be crazily complicated and ineffective. Is there some simple way I don't see? If not, I will post the mess I've already written. :)

Why do I need it?

For better code organisation, I sometimes need to declare multiple classes per one file. This is a problem for my SPL autoloader, that loads files according to class names. Because of that, I need to get every possible filename to load from most probable to the least.

Thanks in advance! :)


Solution

  • Use array_slice() with variable offsets:

    $arr = explode('-', strtolower($str));    
    for ($i = 1, $c = count($arr); $i < $c; $i++) {
        $result[] = implode('-', array_slice($arr, 0, -$i));
    }
    

    Demo