I have quite a few html files with several links in it. E.g.
<div><a href="/location/?latitude=41.7948205&longitude=-72.12729890000003" >location 1</a></div>
<div><a href="/location/?latitude=41.9020418&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&longitude=-72.127299" >location 1</a></div>
<div><a href="/location/?latitude=41.9020418&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.
Here's some PHP code that would do it:
$str = '<div><a href="/location/?latitude=41.7948205&longitude=-72.12729890000003" >location 1</a></div>
<div><a href="/location/?latitude=41.9020418&longitude=-72.07979440000002" >location 2</a></div>
<div><a href="/location/?latitude=41.9020418&longitude=-72.07979440000002" >location 3</a></div>';
$arr = explode("
", $str);
$decimalPlaces = 5;
foreach ($arr as &$line) {
if (preg_match("/latitude=(.*?)&longitude=(.*?)\"/", $line, $matches)) {
$latitudeApprox = round($matches[1], $decimalPlaces);
$longitudeApprox = round($matches[2], $decimalPlaces);
$line = preg_replace("/latitude=.*?&longitude=.*?\"/", "latitude=$latitudeApprox&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&longitude=-72.12729890000003&SOMETHING+ELSE+HERE" >...</a>