正则表达式,用于匹配纬度和经度函数

时间:2019-04-21 02:26:56

标签: php function preg-replace

我的文件中有经度和纬度数据,我正试图通过convertor function来调用。

我正在尝试为$result60行添加功能,但是它不起作用。我正在尝试传递该函数的值,因此它将使用DM方法计算正确的纬度和经度。

尝试

$re60 = '/([EW])([0-9][0-9][0-9])([0-9][0-9])/s';
$str60 = 'E16130';
//$subst60 = '\\3\\2\\1';
$subst60 = DMS2Decimal($degr = \\2, $mins = \\3, $secs = 0, $dir = \\1);
$result60 = preg_replace($re60, $subst60, $str60);
echo "The result of the substitution is ".$result60;

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以使用this RegEx将输入字符串分为3组,其中DMS方法可以调用$1$2$3组以返回{{ 1}}。

RegEx

$decimal

RegEx

代码

/([EWSN])([0-9]{3})([0-9]{2})/s

输出

$str60 = 'E16130';
preg_match_all('/([EWSN])([0-9]{3})([0-9]{2})/s', $str60, $matches);
$result60 = DMS2Decimal($degrees = (int) $matches[2][0], $minutes = (int) $matches[3][0], $seconds = 10, $direction = strtolower($matches[1][0]));

echo "The result of the substitution:  y: " . $result60;

function DMS2Decimal($degrees = 0, $minutes = 0, $seconds = 0, $direction = 'n')
{
    //converts DMS coordinates to decimal
    //returns false on bad inputs, decimal on success

    //direction must be n, s, e or w, case-insensitive
    $d = strtolower($direction);
    $ok = array('n', 's', 'e', 'w');

    //degrees must be integer between 0 and 180
    if (!is_numeric($degrees) || $degrees < 0 || $degrees > 180) {
        $decimal = false;
    }
    //minutes must be integer or float between 0 and 59
    elseif (!is_numeric($minutes) || $minutes < 0 || $minutes > 59) {
        $decimal = false;
    }
    //seconds must be integer or float between 0 and 59
    elseif (!is_numeric($seconds) || $seconds < 0 || $seconds > 59) {
        $decimal = false;
    } elseif (!in_array($d, $ok)) {
        $decimal = false;
    } else {
        //inputs clean, calculate
        $decimal = $degrees + ($minutes / 60) + ($seconds / 3600);

        //reverse for south or west coordinates; north is assumed
        if ($d == 's' || $d == 'w') {
            $decimal *= -1;
        }
    }

    return $decimal;
}