Replace space with comma and pipe interleaved

4

I have a certain string below, as you can see, they are coordinates separated by just one space. See:

  

-23.5209 -46.46466 -23.52008 -46.465952 -23.519253 -46.467239 -23.518808 -46.466901 -23.518738 -46.466848 -23.518411 -46.466597 -23.518349 -46.46658 -23.51834 -46.46657 -23.517974 -46.466157 -23.517879 -46.466052 -23.517859 -46.466074 -23.51733 - 46.466632 -23.516765 -46.467217 -23.516693 -46.467292 -23.516206 -46.467802 -23.516169 -46.467841 -23.516179 -46.467859 -23.516229 -46.467909 -23.516329 -46.467981 -23.518096 -46.469056

Basically the first item is latitude, second is longitude and so on. I need you to stay this way down, which is the separation between latitude and longitude by comma, and between coordinate by pipe. See:

  

-23.5209, -46.46466 | -23.52008, -46.465952 | -23.519253, -46.467239 | -23.518808, -46.466901 | -23.518738, -46.466848 ...

What would be the best way to do this?

    
asked by anonymous 21.06.2017 / 22:45

1 answer

4

You can try to use preg_replace , something like (-[\d.]+)\s(-[\d.]+)(\s|$) , result:

<?php

$x = '-23.5209 -46.46466 -23.52008 -46.465952 -23.519253 -46.467239 -23.518808 -46.466901 -23.518738 -46.466848 -23.518411 -46.466597 -23.518349 -46.46658 -23.51834 -46.46657 -23.517974 -46.466157 -23.517879 -46.466052 -23.517859 -46.466074 -23.51733 -46.466632 -23.516765 -46.467217 -23.516693 -46.467292 -23.516206 -46.467802 -23.516169 -46.467841 -23.516179 -46.467859 -23.516229 -46.467909 -23.516329 -46.467981 -23.518096 -46.469056';

$x = preg_replace('#(-[\d.]+)\s(-[\d.]+)(\s|$)#', '$1,$2|', $x);
$x = rtrim($x, '|'); //Remove o pipe extra no final

echo $x;
  • The (-[\d.]+) looks for a number like -46.467909
  • The \s(-[\d.]+)(\s|$) procuta what comes after "first" number, changes the first space per comma and the second by pipe | , if there is no space at the end adds the pipe (which is removed by rtrim ) .

It will "rotate" the string all overriding, so if you replace the second space directly it will not happen again to pass the second space and accidentally add a comma.

Example on IDEONE

    
21.06.2017 / 22:49