Separate values from a variable

Asked

Viewed 1,503 times

2

Hello friends I need to separate values from a variable I receive values like this:

-4.08768, -63.141322 23/04/2017 22:00:00

need separate values each with a variable type like this:

-4.08768, -63.141322

23/04/2017

22:00:00

I need to send via post to my system but I’m not able to separate someone from this force there to separate this example:

<?php
$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";
echo $variavel;
?>

3 answers

1


$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";

First we remove the space after the comma and then we make an explosion with space so as not to separate the latitude from the longitude

$variavel=str_replace(", ",",",$variavel);

The explosion

$partes = explode(' ',$variavel);

$coordenadas=$partes[0];
$data=$partes[1];
$hora=$partes[2];

And finally we put the space after the comma into the $coordinates variable

$coordenadas=str_replace(",", ",",$coordenadas);

The exit will be

echo $coordenadas; //-4.08768, -63.141322
echo $data; //23/04/2017
echo  $hora; //22:00:00

Putting it all together:

$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";
$variavel=str_replace(", ",",",$variavel);
$partes = explode(' ',$variavel);
$coordenadas=$partes[0];
$data=$partes[1];
$hora=$partes[2];
$coordenadas=str_replace(",", ",",$coordenadas);

echo $coordenadas;
echo $data;
echo  $hora;

ideone example

The same result is obtained as follows::

$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";

$partes = explode(' ',$variavel);

$latitude=$partes[0]; //-4.08768,
$longitude=$partes[1]; //-63.141322
$data=$partes[2]; //23/04/2017
$hora=$partes[3]; // 22:00:00

$latLong=$latitude." ".$longitude; // -4.08768, -63.141322

example - ideone

0

Use a explode to make the separation the way you need ex:

$params = explode(',', $row['variavel']);
$lat = $params[0]; //-4.08768
$lon = $params[1]; //-63.141322 23/04/2017 22:00:00
$val = $params[2]; //0

$saida = $lon.','.$val.','.$lat;

0

Using preg_split, you inform the pattern regex so that the string be divided:

$variavel = "-4.08768, -63.141322 23/04/2017 22:00:00";

$split = preg_split("/\b\s/", $variavel);

var_dump($split);

That way, one will return array three-seater:

array(3) {
  [0]=>
  string(20) "-4.08768, -63.141322"
  [1]=>
  string(10) "23/04/2017"
  [2]=>
  string(8) "22:00:00"
}

See the example on ideone

Browser other questions tagged

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