删除每个第N个字母(循环)

3

我在这里找到了很多对我的问题的回答,但是我没有找到我要找的确切内容。
我需要从数组中删除每个第四个数字,但是开头和结尾要形成一个圆圈,所以如果我在下一个循环中删除第四个数字,它将变成另一个数字(可能是第四个数字,也可能是第三个数字),这取决于字符串中有多少个数字。

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

1
这个循环会一直持续到什么时候? - dfsq
3
请指定一个输入和输出的例子 - 非常难理解你的问题.... 请提供一个输入和输出的示例——很难理解你的问题... - Manse
FYI,你可以使用 $string[$i] 来获取第 i 个字符。 - Salman A
这个循环会一直持续,直到删除所有数字,只剩下最后一个为止。 - ssuperczynski
我会尝试画一张图并解释,给我3分钟。 - ssuperczynski
显示剩余4条评论
4个回答

3
你可以尝试使用preg_replace来完成这个操作:
$string = "12345678901234567890";
$result = preg_replace("/(.{3})\d/", "$1", $string);

0
你可以尝试这个(我的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--;
}

0
一个非正则表达式的解决方案。
$string = "123412341234";
$n = 4;
$newString = implode('',array_map(function($value){return substr($value,0,-1);},str_split($string,$n)));

var_dump($newString);

0
<?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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接