Extract lat/long coordinates from a php string - php

I need to extract latitude and longitude coordinates from a string using php. The string will always be formatted as such:
"(42.32783298989135, -70.99989162915041)"
However the length of each value will vary from use to use. What's the best way to extract the values? Thanks!

You may use sscanf to do this:
sscanf($string, '"(%f, %f)"', $lat, $lng);
Test:
php > sscanf('"(42.32783298989135, -70.99989162915041)"', '"(%f, %f)"', $lat, $lng);
php > var_dump($lat, $lng);
float(42.327832989891)
float(-70.99989162915)

$withoutParentheses = substr($string, 1, -1);
$coordinates = explode(', ', $coordinates);
$longitude = floatval($coordinates[0]);
$latitude = floatval($coordinates[1]);

You could use a regular expression to extract the numbers from the brackets and then use the explode command to split the numbers into an array.
Your regex would be something like
/(-?[0-9]+.[0-9]+, -?[0-9]+.[0-9]+)/
and your delimiter for the explode command would be a comma.

This is what I came up with on my own:
function LatFromString($mCenterString){
//(42.32783298989135, -70.99989162915041)
$mLatLong = explode(",", $mCenterString);
$mLat = '';
if(count($mLatLong) == 2){
$mLat = substr($mLatLong[0], 1);
}
return $mLat;
}
function LongFromString($mCenterString){
//(42.32783298989135, -70.99989162915041)
$mLatLong = explode(",", $mCenterString);
$mLat = '';
if(count($mLatLong) == 2){
$mLong = substr($mLatLong[1], 0, -1);
}
return $mLong;
}
How does this look?

You could do something like this:
$str = "(42.32783298989135, -70.99989162915041)";
function extractlatlong($str){
$latlong = explode(",",$str);
if(count($latlong) == 2){
$lat = preg_replace("%[^0-9.]%","",$latlong[0]);
$long = preg_replace("%[^0-9.]%","",$latlong[1]);
return array("lat"=>$lat,"long"=>$long);
} else {
return NULL;
}
}
print_r(extractlatlong($str));

If you want to use sscanf() (and I probably would), but don't want to lose any precision from casting the numeric values as floats, then use a couple of negated character classes. You don't' have to match the trailing ) to extract what you need.
Code: (Demo)
$latlon = "(42.32783298989135, -70.99989162915041)";
sscanf($latlon, '(%[^,], %[^)]', $lat, $lon);
var_export([$lat, $lon]);
Output as an array of strings:
array (
0 => '42.32783298989135',
1 => '-70.99989162915041',
)
Or if you just want an indexed array of the two values like the above output:
var_export(sscanf($latlon, '(%[^,], %[^)]'));

Related

PHP From string to two variables

In my db there is a table that have some values like this[string]
100/100
50/100
40/80
7/70
I need to change this values in
100%
50%
50%
10%
How can i do this using only PHP/mysql code?
EDIT:this is the code:
foreach ($html->find('div.stat') as $status_raw){
$status = $tag_pic_raw->src;
$status = mysql_real_escape_string($status);
$data->query("INSERT IGNORE INTO `tb` (`value`) VALUES ('".$status."')");
}
I have used a DOM inspector to get info from another site
Used explode() combined with some math.
$str = '40/80';
$vals = explode('/', $str);
$percent = (($vals[0] / $vals[1]) * 100).'%';
echo $percent;
use explode() to divide up the values and then math them.
foreach($array as $val) // assuming all the (##/##) values are in an array
{
$mathProblem = explode("/", $val);
echo (intval($mathProblem[0]) / intval($mathProblem[1]) * 100)."%<br />";
}
You can set up a function similar to this:
function math($one)
{
$new = explode("/", $one);
$math = $new[0] / $new[1];
$answer = $math * 100;
return $answer."%";
}
Then every time you need to query something, you can do it simply by doing this:
foreach ($results as $r)
{
echo math($r);
}
This just makes it (I think) tidier and easier to read.
Use explode() :Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter( / in this case).
$arr=array('80/100','50/100','40/80');
foreach($arr as $str){
$values = explode('/',$str);
echo ((int)$values[0]/(int)$values[1])*100.'%<br/>';
}

How to convert Exponentials to Decimals in PHP

I have a string like this:
9.018E-14
Now I want to convert to this to the normal decimal numbers.
MyGeekPal has a nice article on it.
Code:
<?php
$total_time = 2.8848648071289E-5;
echo exp2dec($total_time);
function exp2dec($number) {
preg_match('/(.*)E-(.*)/', str_replace(".", "", $number), $matches);
$num = "0.";
while ($matches[2] > 0) {
$num .= "0";
$matches[2]--;
}
return $num . $matches[1];
}
?>
If your input is a float
If you have $number = 0.00023459 then printing this value in PHP will probably result in this exponential format. It doesn't mean the variable is stored that way; it's just an output artefact.
Use printf to work around this and gain control over your numeric output.
If your input is a string
Why the complexity?
$matches = Array();
if (preg_match('/(.*)E-(.*)/', $number, $matches)) {
$number = $matches[1] * pow(10, -1*$matches[2]);
}
Though you can tighten up the regex a bit:
$matches = Array();
if (preg_match('/(\d+(?:\.\d+)?)E(-?\d+)/i', $number, $matches)) {
$number = (float)$matches[1] * pow(10, (int)$matches[2]);
}
Live demo
EDIT: Here is some PHP magic:
$stringval = "12e-3";
$numericval = 0 + $stringval;
From the PHP docs:
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
If you need a more flexible format (e.g. extract four numbers from the same string), use sscanf like this:
$stringval = "12e-3";
$numericval = sscanf($stringval, "%f")[0];
echo $numericval;

Take a part of a string (PHP)

We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?
That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);
Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];
$StringArray = explode ( ":" , $string)
By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);
it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);
the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

Remove last character from a variable and then multiply against another variable

I have a whole bunch of percentages stored as XX% (e.g. 12%, 50%, etc..) I need to remove the percentage sign and then multiply the percent against another variable thats just a number (e.g. 1000, 12000) and then output the result. Is there a simple way to strip the percentage sign and then calculate the output with PHP? Or should I consider some sort of JS solution?
You could use rtrim():
$value = ((int) rtrim('12%', '%')) * 1000';
Edit
You don't strictly need to call rtrim() , as it casts to an int ok with the percentage sign. It is probably cleaner to strip it though.
var_dump (12 === (int) '12%');
//output: bool(true)
You can make use of preg_replace_callback as:
$input = '12%, 50%';
$input = preg_replace_callback("|(\d+)%|","replace_precent",$input);
echo $input; // 12000, 50000
function replace_precent($matches) {
return $matches[1] * 1000;
}
Try this:
$number = str_replace('%', '', '100%');
$result = intval($number) * 5000; // or whatever number
echo $result;
If you use trim() or str_replace() in PHP you can remove the percent sign. Then, you should be able to multiply the resulting number (php is weakly typed after all).
<?php
$number = str_replace("%", "", $percentString);
$newNumber = ((int) $number) * 1000;
echo $newNumber;
?>
You can use str_replace. You can also pass an array of subjects into str_replace to have them all replaced.
<?php
$number = str_replace("%", "", $percentage);
$result = $number * $other_var;
print $result;
?>
<?php
$input=array('15%','50%','10.99%','21.5%');
$multiplier=1000;
foreach($input as $n){
$z=floatval($n)*$multiplier;
print("$z<br>");
}
?>

string slicing, php

is there a way to slice a string lets say i have this variable
$output=Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87
i want to slice it in a way i want to pull latitude and longitude values in to seperate variables, subtok is not serving the purpose
You don't need a regular expression for this; use explode() to split up the string, first by &, and then by =, which you can use to effectively parse it into a nice little array mapping names to values.
$output='Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
parse_str($output, $array);
$latitude = $array['latitude'];
You could also just do
parse_str($output);
echo $latitude;
I think using an array is better as you are not creating variables all over the place, which could potentially be dangerous (like register_globals) if you don't trust the input string.
It looks likes it's coming from an URL, although the URL encoding is gone.
I second the suggestions of using explode() or preg_split() but you might also be interested in parse_str().
$output = "City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87";
parse_str($output, $results);
$lat = $results['Latitude'];
$lon = $results['Longitude'];
I'm not sure exactly what you're demonstrating in your code, maybe it's just some typos, is the "$output" the name of the variable, or part of the string?
Assuming it's the name of the variable, and you just forgot to put the quotes on the string, you have a couple options:
$sliced = explode('&', $output)
This will create an array with values: "Country=UNITED STATES(US) ", "City=Scottsdale, AZ ", etc.
$sliced = preg_split('/[&=]/', $output);
This will create an array with alternating elements being the "variables" and their values: "Country", "UNITED STATES(US) ", "City", "Scottsdale, AZ ", etc.
You could do the following:
$output = 'Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
$strs = explode('&', $output);
foreach ($strs as $str) {
list($var, $val) = explode('=',$str);
$$var = trim($val);
}
This would give you variables such as $Latitude and $Longitude that are set to the value in the key/value pair.
All of the other Answers are Insufficient. This Should Work Every Time!
function slice($string, $start){
$st = $string; $s = $start; $l = strlen($st); $a = func_get_args();
$e = isset($a[2]) ? $a[2] : $l;
$f = $e-$s;
$p = $e < 0 && $s > 0 ? $l+$f : $f;
return substr($st, $s, $p);
}
I suggest you read about regular expressions in the PHP help.

Categories