开发者

php sscanf problem

开发者 https://www.devze.com 2023-03-28 10:58 出处:网络
I have this string: City Lat/Lon: (50.7708) / (6.1053) and I try to extract those two numbers with sscanf in php this way:

I have this string:

City Lat/Lon: (50.7708) / (6.1053)

and I try to extract those two numbers with sscanf in php this way:

$result = post_request('http://www.ip-address.org/lookup/ip-locator.php', $post_data);
$start =strpos($result['content'], "City Lat/Lon");
$end = strpos($result['content'], "IP Language");
$sub = substr($result['content'],$start,$end-$start);
sscanf($sub, "City Lat/Lon: (%f) / (6.1053)",$asd);
echo $asd;
开发者_如何学编程

but it doesn't give me any result nor errors what should I change?

it works though this way

sscanf("City Lat/Lon: (50.7708) / (6.1053)", "City Lat/Lon: (%f) / (%f)",$asd,$wer);


It appears you're using the post_request() function found here.

If so, your $sub variable contains various HTML tags found in the response. For example if you attempt:

var_dump($sub) // Outputs: string 'City Lat/Lon:</th><td class='lookup'> (50.7708) / (6.1053)</td></tr><tr><th>' (length=78)

Instead of sscanf, you can try to match the latitude and longitude using a regular expression (as suggested by @Headshota). For example one possible solution:

//...

preg_match('#\((?<lat>-?[0-9.]+)\) / \((?<lon>-?[0-9.]+)\)#', $sub, $matches);
echo $matches["lat"]; // Outputs 50.7708
echo $matches["lon"]; // Outputs 6.1053


Works for me:

$sub = 'City Lat/Lon: (50.7708) / (6.1053)';
var_dump( sscanf($sub, "City Lat/Lon: (%f) / (6.1053)",$asd), $asd);

... prints:

int(1)
float(50.7708)

The error can be in your exact test code or somewhere else.


Use the regex:

 preg_match_all("/(\([0-9.]+\))/");

this will return an array with your values.

0

精彩评论

暂无评论...
验证码 换一张
取 消