Skip to content
Advertisement

Remove the comma and number of a string

I tried to find a solution, but no luck so far.

I need to remove the comma and third number (,1482.36 / ,73.50 / ,-472.15 / ,472.15) of each ‘block’ in a given string like the example bellow:

-53.71758699417,-27.70134039904,1482.36 -53.71672868729,-27.70172036343,73.50 -53.71649265289,-27.70200533586,-472.15 -53.71661067009,-27.70205283119,472.15 

Any clues of how I could do it in PHP?

Thanks

Advertisement

Answer

You will need to use preg_split actually to split the string based on either comma or a space. Simple explode won’t work.

You can loop over the array obtained and skip all those indices that are divisible by 3.

<?php

$str = '-53.71758699417,-27.70134039904,1482.36 -53.71672868729,-27.70172036343,73.50 -53.71649265289,-27.70200533586,-472.15 -53.71661067009,-27.70205283119,472.15';

$data = preg_split("/[,s]/",$str);

$result = [];

foreach($data as $index => $val){
    if(($index + 1) % 3 != 0){
        $result[] = $val;
    }
}

echo implode(",",$result);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement