3

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

apxcode
  • 7,696
  • 7
  • 30
  • 41
Petr Cibulka
  • 2,452
  • 4
  • 28
  • 45

2 Answers2

3

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

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

There you go! I just tested and it prints exactly what you need =)

<?php 
$str = "Field-Text-Datepicker";
$str = strtolower($str);
$array = explode('-',$str);
$count = count($array);
$output_array = [];
for($i=1;$i<=$count;$i++)
    $output_array[$count-$i] = implode('-',array_slice($array,0,$i));

var_dump($output_array); 
?>
Magus
  • 2,905
  • 28
  • 36