Reputation: 3416
I found here many responses for my question but I cat't find exactly what I am looking for.
I have to remove every 4th digit from an array, but beginning and the end making a circle, so If I remove 4th digit in next loop It's gonna be another digit (maybe 4th maybe 3rd) It's depend how many digit we have in string
$string = "456345673474562653265326";
$chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
$result = array();
for ($i = 0; $i < $size; $i += 4)
{
$result[] = $chars[$i];
}
Upvotes: 3
Views: 1845
Reputation: 34284
<?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";
}
?>
Output:
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
Upvotes: 0
Reputation: 212452
A non-regexp solution
$string = "123412341234";
$n = 4;
$newString = implode('',array_map(function($value){return substr($value,0,-1);},str_split($string,$n)));
var_dump($newString);
Upvotes: 0
Reputation: 2496
You can try this (my PHP is rusty so I'm not sure whether erasing this way will work):
$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--;
}
Upvotes: 0
Reputation: 2358
You could try doing this with preg_replace
:
$string = "12345678901234567890";
$result = preg_replace("/(.{3})\d/", "$1", $string);
Upvotes: 3