Up until now, we've only used our custom-built PEG parser to check if an input string conforms to a given grammar (meaning, we can tell if an input string contains a valid mathematical expression or not). The next logical step is to actually evaluate these expressions (for example, determining that '(1 + 2) * 3'
evaluates to '9'
).
As you have already seen, each match_*
function returns an array with additional information on the matched string. Within the parser, you can register custom functions that will be called when a given symbol is matched. Let's start with something simple and try to convert numbers that are matched by our grammar to actual PHP integer or float values. For this, start by modifying the Integer
and Decimal
rules in your grammar as follows:
Integer: value:('-'? Digit+) function value(array &$result, array $sub) { $result['value'] = (int) $sub['text']; } Double: value:('-'? Digit* '.' Digit+) function value(array &...