【问题标题】:remove every Nth letter (loop)删除每 N 个字母(循环)
【发布时间】:2012-02-18 11:34:52
【问题描述】:

我在这里找到了很多对我的问题的回答,但我找不到我正在寻找的东西。
我必须从数组中删除每个第 4 位,但开始和结束都画一个圆圈,所以如果我在下一个循环中删除第 4 位,它将是另一个数字(可能是第 4 位,也可能是第 3 位)这取决于我们在字符串中有多少位

$string = "456345673474562653265326";
$chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
$result = array();
for ($i = 0; $i < $size; $i += 4) 
{
    $result[] = $chars[$i];
}

【问题讨论】:

  • 这个循环一直持续到 what?
  • “开始和结束组成一个圆圈”是什么意思?
  • 请指定输入和输出的示例-很难理解您的问题....
  • 仅供参考,您可以通过$string[$i] 获取ith 字符。
  • 1.这个循环一直持续到删除所有留下最后一位的数字

标签: php arrays loops


【解决方案1】:
<?php
$string = "abcdef";
$chars = str_split($string);

$i = 0;
while (count($chars) > 1) {
    $i += 3;
    $n = count($chars);
    if ($i >= $n)
        $i %= $n;

    unset($chars[$i]);
    $chars = array_values($chars);

    echo "DEBUG LOG: n: $n, i: $i; s: " . implode($chars, '') . "\n";
}
?>

输出:

DEBUG LOG: n: 6, i: 3; s: abcef
DEBUG LOG: n: 5, i: 1; s: acef
DEBUG LOG: n: 4, i: 0; s: cef
DEBUG LOG: n: 3, i: 0; s: ef
DEBUG LOG: n: 2, i: 1; s: e

【讨论】:

    【解决方案2】:

    非正则表达式解决方案

    $string = "123412341234";
    $n = 4;
    $newString = implode('',array_map(function($value){return substr($value,0,-1);},str_split($string,$n)));
    
    var_dump($newString);
    

    【讨论】:

      【解决方案3】:

      你可以试试这个(我的 PHP 生锈了,所以我不确定这样擦除是否有效):

      $string = "123412341234";
      $result = array();
      $n = 4; // Number of chars to skip at each iteration
      
      $idx = 0; // Index of the next char to erase
      $len = strlen($string);
      while($len > 1) { // Loop until only one char is left
          $idx = ($idx + $n) % $len; // Increase index, restart at the beginning of the string if we are past the end
          $result[] = $string[$idx];      
          $string[$idx] = ''; // Erase char
          $idx--; // The index moves back because we erased a char
          $len--;
      }
      

      【讨论】:

        【解决方案4】:

        您可以尝试使用preg_replace

        $string = "12345678901234567890";
        $result = preg_replace("/(.{3})\d/", "$1", $string);
        

        【讨论】:

          猜你喜欢
          • 2020-12-21
          • 2020-04-24
          • 1970-01-01
          • 1970-01-01
          • 2015-11-16
          • 1970-01-01
          • 2022-09-27
          • 1970-01-01
          • 2020-01-10
          相关资源
          最近更新 更多