Search code examples
phpgoogle-mapsgpssubstringexplode

Explode function to extract values from DMS notation


I have a table with locations stored in the format:

30°28'25"  
68°28'43"

In the process of converting from DMS to DEC, I'd need a function to convert the string 68°28'43" (no spaces among values-symbols) into

$deg = 68  
$min = 28  
$sec = 43 

Or something similar. Thanks


Solution

  • Simply use preg_match_all :)

    the following regex simply captures every digits (\d) which are contains exactly 2 numbers ({2}) and group them (the braces around the expression)

    <?php
    $value = "68°28'43\"";
    preg_match_all('/(\d{2})/', $value, $matches);
    
    print_r($matches);
    

    $matches would be an array with the captured results (the digits)

    Array
    (
        [0] => Array
            (
                [0] => 68
                [1] => 28
                [2] => 43
            )
    
        [1] => Array
            (
                [0] => 68
                [1] => 28
                [2] => 43
            )
    
    )
    

    And then you can simply assign it to your variables with the list() function as follow:

    list($deg, $min, $sec) = $matches[0];
    
    echo $deg; // 68
    echo $min; // 28
    echo $sec; // 43