Reputation: 33
I want to remove the words from a string by a given position from input, also the following words with the position from input.
EXAMPLE:
position = 2
string = aa bb cc dd ee ff gg hh
Will become: aa cc ee gg
I have:
$delete = $position - 1;
$words = explode(" ", $string);
if(isset($words[$delete])) unset($words[$delete]);
$string = implode(" ", $words);
echo $string;}
That displays
aa cc dd ee ff gg hh
Upvotes: 0
Views: 828
Reputation: 780851
$position = 2;
$string = 'aa bb cc dd ee ff gg hh';
$arr=explode(' ', $string);
$count = count($arr);
// $position-1 because PHP arrays are 0-based, but the $position is 1-based.
for ($i = $position-1; $i < $count; $i += $position) {
unset($arr[$i]);
}
$new_string = implode(' ', $arr);
echo $new_string;
Upvotes: 1
Reputation: 11328
$position = 2;
$string = 'aa bb cc dd ee ff gg hh';
$arr=explode(' ', $string);
$final_str='';
for($i=0;$i<count($arr);$i++) {
if($i%$position==0) {
$final_str.=$arr[$i].' ';
}
}
echo $final_str;
Upvotes: 0
Reputation: 1231
This is untested but i think this is what you are looking for. This will remove every 2nd word after a deletion or when starting to count the words.
$deletePos = 2;
$words = explode(" ", $string);
$i = 1;
foreach($words as $key => $word) {
if ($i == $deletePos) {
unset($words[$key]);
$i = 1;
continue;
}
$i++;
}
Upvotes: 1