Remove Words step by step from Left to Right in PHP String ← (PHP)

I have a string and I want to remove words from its left to right step by step.

$n = 'Dettol Antibacterial Surface Cleansing Wipes';
$arr = str_word_count($n, 1);
for ($x = 0; $x < count($arr); $x++) {
  echo $arr[$x].'<br />';
}

What I want is to get 4 strings out of it removing words left to right.

string1= Antibacterial Surface Cleansing Wipes
string2= Surface Cleansing Wipes
string3= Cleansing Wipes
string4= Wipes

Answer



Solution:

Quick and dirty way is to use explode, remove first element by array_shift and then implode.

$n = 'Dettol Antibacterial Surface Cleansing Wipes';
$words = explode(' ', $n);

while (!empty($words)) {
    array_shift($words);
    echo implode(' ', $words) . '<br>';
}

Source