Evaluating expressions

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

Get PHP 7 Programming Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.