I have a few regexes in an array and testing some strings against them.
$results = array();
$testString = 'The distance is 0,1 km. It is above 200 m.';
$regex = array(
'distance' => '/The distance is (?P<distance>\d+) m\./',
'distance' => '/The distance is (?P<distance>\d+(,\d+)?) km\./',
'height' => '/It is above (?P<height>\d+) m\./'
'height' => '/It is above (?P<height>\d+(,\d+)?) km\./'
);
foreach ($regex as $key => $reg) {
if (preg_match($reg, $testString, $matches)) {
$results[] = array('type' => $key, 'value' => $matches[$key]);
}
}
I want to store the results as “meters”, but in the test string above, the “km”-regex is matched.
Can I add some magic to the regex code, so it transforms the matched 0,1 into 100 (= match * 1000)?
It would be perfect to do it right in the regex code, so I dont have to add exceptions into the PHP code.
Thank you for your help! 🙂
Wulf
If you want dirty tricks, you could do something like this after assigning the string:
http://ideone.com/Sk2um
PS: you can’t do that directly in your regex (in PHP anyway), you have to use some code somewhere for it to work.
Explanation: It matches numbers with
kmafter them, capturing the integer and decimal parts, then replacing them with the results of the PHP code in the replacement:The code is evaluated because the
/eflag is used.