doujiao1538 2014-10-06 18:00
浏览 22
已采纳

解析文件中的数据后使用舍入功能

I have quite a few html files with several links in it. E.g.

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

I want to round the longitude values to 6 decimal places. E.g.

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

I'm a noob when it comes to file parsing and don't know if this is possible. I would appreciate any pointers and guidance.

  • 写回答

1条回答 默认 最新

  • dongsi073898 2014-10-06 18:30
    关注

    Here's some PHP code that would do it:

    $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("
    ", $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("
    ", $arr);
    echo $str;
    

    Note that the regex for pulling out the longitude is not very robust. It assumes you never have a case like this, for example:

    <a href="/location/?latitude=41.7948205&amp;longitude=-72.12729890000003&amp;SOMETHING+ELSE+HERE" >...</a>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害