When i read an array i got value set like this
"lat" : -37.8087928,. I want to only
-37.8087928 part. what is the correct way to do that.
I did it in this way:
$value = '"lat" : -37.8087928,';
$ex = explode(':', $value);
$ex2 = explode(',', $ex);
is this correct or what is the correct way, thank you all
$value = '"lat" : -37.8087928,'; $final_value = preg_replace("/[^0-9.\-]/", "", $value);
The code above will strip all characters that are not numeric, dot or hyphen.
You can delete all spaces in a string
$stingname=" test manish "; str_replace(" ","",$stingname); echo $stingname;
that's object notation. you might want to try
$locations = json_decode($value)
then you could access it like this:
echo $locations->lat; // prints -37.8087928
if you don't want to do that you could do:
$locationArray = explode($value, ':'); // returns [0: 'lat', 1: -37.8087928] echo trim($locationArray); // prints -37.8087928. trim to get rid of whitespace
The correct method depends on the variability of the input string - "like this" is not an adequate explanation.
Your parser suffices - but has no error handling, nor any means of dealing with a differently formatted string. Using a regexp as described by jorge is more robust, however may not cope with some input scenarios.
The input string you provided looks very like JSON - in which case you should be using a JSON parser - PHP has a very good one built in - which will simply reject non-conformant input.
There is no problem in your approach. But you can use also this which is more easy to understand:
$value = '"lat" : -37.8087928,'; echo $float = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
Hope this help you!
you can read more about it here
People are suggesting regex's and explodes, why? Thats slow and not needed. If you have a fixed string, you can do it with some string functions:
$value = '"lat" : -37.8087928,'; $result = trim( substr($value, strpos($value,":")+1) ), " ,");
This works by finding the
: in that string and substract it till the end. Then with a trim you remove the spaces and the comma. If the comma is ALWAYS there, you can do this, and drop the trim:
$result = substr($value, strpos($value,":")+1), -1 );// till -1 from the end