Replace space by comma and pipe interchangeably

Asked

Viewed 219 times

4

I have a certain string below, as you can see, are coordinates separated only by a 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 it to stay this way below, 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 better way to do it?

1 answer

4


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

<?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 o que vem após "primeiro" numero, troca o primeiro espaço por virgula e o segundo por pipe |, if there is no space at the end adds the pipe (which is removed by rtrim).

It will "rotate" the string all replacing, this way if replace the second space directly will not occur it pass again in the second space and accidentally add a comma.

Example in IDEONE

  • From what I understand, the last coordinate does not fit the regex. If you remove the \s of the end ai yes it works. Think you can influence removing?! What the \s does exactly!?

  • @acklay \s is a meta character of match espaços; maybe \s? to make optional match?

  • 1

    @Jeffersonquesado did not understand if you are telling me something or if you are asking a question. xD

  • @acklay I’ll rewrite. 1) \s house any and all space, as \d box digits; 2) \s? makes the presence of spacing optional, can solve the problem of the last coordinate

Browser other questions tagged

You are not signed in. Login or sign up in order to post.