Wasn't sure about the explode() idea since I dunno if the colon may occur anywhere else but in theory it would be more efficient if benchmarked...
The maths works too.. makes nastly looking regex though since there seems to be random whitespace between the pos/neg signs....
Code: Select all
$file = '/full/path/to/file.txt';
$string = file_get_contents($file);
$results = array();
//LA
preg_match('#^LA\:(?: )*(.*)#m', $string, $match);
$results['LA'] = trim($match[1]);
//ST
preg_match('#^ST\:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$results['ST'] = trim($match[1].$match[2]);
//CO
preg_match('#^LA\:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$results['CO'] = trim($match[1].$match[2]);
//X
preg_match('#^\+X:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$X0 = trim($match[1].$match[2]);
preg_match('#\-X:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$X1 = trim($match[1].$match[2]);
$results['X'] = $X0 - $X1;
//Y
preg_match('#^\+Y:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$Y0 = trim($match[1].$match[2]);
preg_match('#\-Y:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$Y1 = trim($match[1].$match[2]);
$results['Y'] = $Y0 - $Y1;
//Just to show the output <-- delete this
print_r($results);
If you need a easy to use function:
Code: Select all
function getData($file) {
$string = file_get_contents($file);
$results = array();
//LA
preg_match('#^LA\:(?: )*(.*)#m', $string, $match);
$results['LA'] = trim($match[1]);
//ST
preg_match('#^ST\:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$results['ST'] = trim($match[1].$match[2]);
//CO
preg_match('#^LA\:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$results['CO'] = trim($match[1].$match[2]);
//X
preg_match('#^\+X:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$X0 = trim($match[1].$match[2]);
preg_match('#\-X:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$X1 = trim($match[1].$match[2]);
$results['X'] = $X0 - $X1;
//Y
preg_match('#^\+Y:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$Y0 = trim($match[1].$match[2]);
preg_match('#\-Y:(?: )*([\-\+])?(?: )*(.*)#m', $string, $match);
$Y1 = trim($match[1].$match[2]);
$results['Y'] = $Y0 - $Y1;
return $results;
}
//Example
$data = getData('full/path/to/file.txt');
print_r($data); //Test only
Essentially... it opens the file and reads ALL the data. Runs some regex to get what it needs then does the calulation on the bits you need. It adds everything to an array so you can call it back easily.
Hope it helps.