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

时间:2012-01-25 09:09:49

标签: php arrays loops

我在这里找到了许多回答我的问题,但我找不到我要找的确切内容 我必须从数组中删除每个第4个数字,但是开始和结束形成一个圆圈,所以如果我在下一个循环中删除第4个数字它将是另一个数字(可能是第4个可能是第3个)这取决于我们在字符串中有多少个数字< / p>

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

4 个答案:

答案 0 :(得分:3)

您可以尝试使用preg_replace

执行此操作
$string = "12345678901234567890";
$result = preg_replace("/(.{3})\d/", "$1", $string);

答案 1 :(得分: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--;
}

答案 2 :(得分:0)

非正则表达式解决方案

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

var_dump($newString);

答案 3 :(得分: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