Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! :)

like image 954
Petr Cibulka Avatar asked Aug 29 '26 19:08

Petr Cibulka


1 Answers

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

like image 153
Amal Murali Avatar answered Sep 04 '26 10:09

Amal Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!