How to implement Lexical Analysis and Custom language with PHP
In this article Xiaobian for you to introduce in detail "PHP how to achieve lexical analysis and custom language", the content is detailed, the steps are clear, the details are handled properly, I hope that this "PHP how to achieve lexical analysis and custom language" article can help you solve your doubts, following the editor's ideas slowly in depth, together to learn new knowledge.
There was a requirement in the previous project. The business staff wrote some custom formulas in Chinese, and then we needed to implement the background to return the results to the interface, so we wrote this lexical analyzer based on the finite state machine, which is relatively simple. I hope to be able to throw a brick to attract jade.
I. Analysis of requirements
Enter a Chinese formula and return the result, such as:
Existing salary = 10000; personal tax starting point = 3000; current year = 2021; if (current year = 2022) {personal tax starting point = 5000;} return (existing salary-personal tax starting point) * 0.2
Second, to meet the needs
The original idea is to use string substitution to replace Chinese keywords with php keywords, and then call eval to execute, which is indeed possible, but it is not very beautiful and cannot be dynamically parsed. I thought it would be nice to implement a simple lexical analysis and then convert the lexical analysis into php code with ast. The current version does not use abstract syntax trees to generate code, all using string concatenation.