分析文件中的数据后使用舍入函数

Use rounding function after parsing data from a file

本文关键字:舍入 函数 数据 文件      更新时间:2023-10-16

我有很多html文件,其中有几个链接。例如

<div><a href="/location/?latitude=41.7948205&amp;longitude=-72.12729890000003" >location 1</a></div>
<div><a href="/location/?latitude=41.9020418&amp;longitude=-72.07979440000002" >location 2</a></div>

我想把经度值四舍五入到小数点后6位。例如

<div><a href="/location/?latitude=41.7948205&amp;longitude=-72.127299" >location 1</a></div>
<div><a href="/location/?latitude=41.9020418&amp;longitude=-72.079794" >location 2</a></div>

当涉及到文件解析时,我是一个傻瓜,不知道这是否可能。如果有任何建议和指导,我将不胜感激。

下面是一些可以做到这一点的PHP代码:

$str = '<div><a href="/location/?latitude=41.7948205&amp;longitude=-72.12729890000003" >location 1</a></div>
<div><a href="/location/?latitude=41.9020418&amp;longitude=-72.07979440000002" >location 2</a></div>
<div><a href="/location/?latitude=41.9020418&amp;longitude=-72.07979440000002" >location 3</a></div>';
$arr = explode("n", $str);
$decimalPlaces = 5;
foreach ($arr as &$line) {
     if (preg_match("/latitude=(.*?)&amp;longitude=(.*?)"/", $line, $matches)) {
         $latitudeApprox = round($matches[1], $decimalPlaces);
         $longitudeApprox = round($matches[2], $decimalPlaces);
         $line = preg_replace("/latitude=.*?&amp;longitude=.*?"/", "latitude=$latitudeApprox&amp;longitude=$longitudeApprox"", $line);
    }
}
$str = implode("n", $arr);
echo $str;

请注意,用于提取经度的正则表达式不是很健壮。它假设你从未遇到过这样的情况,例如:

<a href="/location/?latitude=41.7948205&amp;longitude=-72.12729890000003&amp;SOMETHING+ELSE+HERE" >...</a>