按位置从字符串中删除单词


remove words from string by position php

我想从输入中删除给定位置的字符串中的单词,以及以下具有输入位置的单词。

的例子:

position = 2

string = aa bb cc dd ee ff gg hh

将变成:aa cc ee gg

:

$delete = $position - 1;
$words = explode(" ", $string);
if(isset($words[$delete])) unset($words[$delete]);
$string = implode(" ", $words);
echo $string;}
显示

aa cc dd ee ff gg hh

这是未经测试的,但我认为这是你正在寻找的。这将在删除后或开始计数单词时每隔两个单词删除一次。

$deletePos = 2;
$words = explode(" ", $string);
$i = 1;
foreach($words as $key => $word) {
  if ($i == $deletePos) {
    unset($words[$key]);
    $i = 1;
    continue;
  }
  $i++;
}
$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;
 $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;