Question

If I have this string:

k6s6k6s6c1u6t661w651z6k6z6z6k611

How can delete all the characters in even-numbers position? (2, 4, 6...)

kskscut6w5zkzzk1

I tried:

$str = "k6s6k6s6c1u6t661w651z6k6z6z6k611";
$arr = str_split($str, 2);
print_r(substr_replace($arr ,"",-1));

Its OK. But it doesn't seem to work if I want to continue the script with the trimmed string.

Array
(
    [0] => k
    [1] => s
    [2] => k
    [3] => s
    [4] => c
    [5] => u
    [6] => t
    [7] => 6
    [8] => w
    [9] => 5
    [10] => z
    [11] => k
    [12] => z
    [13] => z
    [14] => k
    [15] => 1
)

I want raw string. Not arrays.

kskscut6w5zkzzk1

I could use explode too, but they are not always fixed characters.

This should be simple. Thanks in advance.

Was it helpful?

Solution

Use implode.

$str = "k6s6k6s6c1u6t661w651z6k6z6z6k611";
$arr = str_split($str, 2);
$str2 = implode("", substr_replace($arr ,"",-1));
echo $str2;

OTHER TIPS

$str = "k6s6k6s6c1u6t661w651z6k6z6z6k611";
$new_str = '';
$str_length =  strlen($str);
for($i=0; $i< $str_length; $i++)
{
    if($i%2==0) $new_str .= $str{$i};
}

echo $new_str;

The output: kskscut6w5zkzzk1

You can try

preg_replace('/(.)(.)/', '$1', $str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top