phpstringextractscanf

sscanf() not parsing latitude/longitude string


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

Solution

  • 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