php - 从文件解析数据后使用舍入函数

标签 php c++ c parsing rounding

我有很多 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>

关于php - 从文件解析数据后使用舍入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26222037/

相关文章:

php - 从mysql数据库授权用户

php - 在 pyrocms 中禁用缓存

c++ - 如何在不使用程序集的情况下以独立于 cpu 的方式从 C/C++ 应用程序进行 Linux 系统调用?

c - 为什么我在尝试使用免费图像库保存 opengl 缓冲区时总是得到黑色图像?

php - 低效的 SQL 查询

php - 连接两个 MySQL 查询

c++ - 在 if 条件中声明变量有什么问题?

python - 如何使 Python 模拟从基类派生?

c - 如何在c中读取TIFF文件头?

c - C中的Gabor滤波器卷积矩阵