当前位置: 动力学知识库 > 问答 > 编程问答 >

how to remove unwanted characters from string in PHP

问题描述:

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);

and

$ex2 = explode(',', $ex[1]);

final resualt $ex2[0]

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;

Result

testmanish
网友答案:

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[1]); // 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
分享给朋友:
您可能感兴趣的文章:
随机阅读: