当前位置: 首页 > 编程文章 >

基于有限状态机的PHP中文词法分析器实现

基于有限状态机的PHP中文词法分析器实现

作者:顾景时间:2025-05-14 17:27:44浏览:597

本文介绍了一种基于有限状态机在PHP中实现的中文词法分析器,用于解析业务人员编写的中文自定义公式。该方案将中文关键字映射为PHP语法,通过词法生成与代码转换,支持动态执行如薪资计算等复杂逻辑,适用于OA系统等需要灵活公式配置的场景。

本文目录展开

此前项目中存在一项需求:业务人员需使用中文编写自定义公式,由后台执行并返回结果至前端界面。为此,笔者基于有限状态机制开发了这款词法分析器。其结构相对简单,旨在起到抛砖引玉之效。

一、分析需求

输入内容为中文公式,输出对应计算结果,示例如下:

现有薪资=10000; 个税起点=3000; 当前年份=2026; 如果(当前年份=2026){ 个税起点=5000; } 返回 (现有薪资-个税起点) * 0.2;

二、实现需求

初期思路是采用字符串替换策略,将中文关键字转换为PHP关键字后调用eval执行。虽可行但不够优雅且无法实现动态解析。因此决定自行实现简易词法分析器,结合抽象语法树(AST)将词法转为PHP代码执行。当前版本未使用AST生成代码,而是采用全字符串拼接方式。

<?php

/**

 * Class Lexer

 * @package Sett\OaLang

 * 词法分析器
   */
   class Lexer {
   // 内置关键字集合
   public $keywordList = [];
   // 内置操作符集合
   public $operatorList = [
       "+", "-", "*", "/", "=", ">", "<", "!", "(", ")", "{", "}", ",", ";"
   ];
   // 源代码
   private $input;
   // 当前的字符
   private $currChar;
   // 当前字符位置
   private $currCharPos = 0;
   // 结束符
   private $eof = "eof";
   // 当前编码
   private $currEncode  = "UTF-8";

   // 内置关键字
   public const VAR = "variable";
   public const STR = "string";
   public const KW  = "keyword";
   public const OPR = "operator";
   public const INT = "integer";
   public const NIL = "null";


    /**
     * Lexer constructor.
     * @param string $input
     */
    public function __construct(string $input) {
        $this->input    = $input;
        $this->currChar = mb_substr($this->input, $this->currCharPos, 1);
    }
    
    /**
     * @param array $keywordList
     */
    public function setKeywordList($keywordList) {
        $this->keywordList = $keywordList;
    }
    
    /**
     * @return array
     * @throws Exception
     */
    public function parseInput() {
        if ($this->input == "") {
            throw new Exception("code can not be empty");
        }
        $tokens = [];
        do {
            $token = $this->nextToken();
            if ($token["type"] != "eof") {
                $tokens[] = $token;
            }
            if ($token["type"] == self::KW) {
                $tokens[] = $this->makeToken(self::NIL, " ");
            }
        } while ($token["type"] != "eof");
        return $tokens;
    }
    
    /**
     * @return array
     */
    public function nextToken() {
        $this->skipBlankChar();
        $this->currChar == "" && $this->currChar = $this->eof;
        if ($this->isCnLetter()) {
            $word = $this->matchUntilNextCharIsNotCn();
            if ($this->isKeyword($word)) {
                $this->currCharPos -= 1;
                return $this->currToken(static::KW, $word);
            }
            // 不是关键字的全部归为变量
            return $this->makeToken(static::VAR, $word);
        }
        // 如果是操作符
        if ($this->isOperator()) {
            return $this->currToken(static::OPR, $this->currChar);
        }
        // 如果是数字
        if ($this->isNumber()) {
            return $this->currToken(static::INT, $this->currChar);
        }
        // 如果是字符串
        if ($str = $this->isStr()) {
            return $this->currToken(static::STR, $str);
        }
        // 如果是变量
        if ($this->isVar()) {
            $word = $this->matchVar();
            if ($this->isKeyword($word)) {
                return $this->currToken(static::KW, $word);
            }
            return $this->makeToken(static::VAR, $word);
        }
        if ($this->currChar == $this->eof) {
            return $this->currToken('eof', $this->currChar);
        }
        return $this->currToken(static::VAR, $this->currChar);
    }
    
    /**
     * @param string $input
     * @return string
     */
    private function matchVar(string $input = "") {
        $word = $input ?: '';
        while ($this->isVar()) {
            $word .= $this->currChar;
            $this->nextChar();
        }
        return $word;
    }
    
    /**
     * @return bool
     * 是否为普通变量
     */
    private function isVar() {
        return $this->isCnLetter() || $this->isEnLetter();
    }


    /**
     * 跳过空白字符
     */
    private function skipBlankChar() {
        while (ord($this->currChar) == 10 ||
            ord($this->currChar) == 13 ||
            ord($this->currChar) == 32) {
            $this->nextChar();
        }
    }
    
    /**
     * @param string $type
     * @param $word
     * @return array
     * 记录当前token和下一个字符
     */
    private function currToken(string $type, $word) {
        $token = $this->makeToken($type, $word);
        $this->nextChar();
        return $token;
    }
    
    /**
     * @param string $type
     * @param string $char
     * @return array
     */
    private function makeToken(string $type, string $char) {
        return ["type" => $type, "char" => $char, "pos" => $this->currCharPos];
    }


    /**
     * @return bool
     * 判断是否是英文字符
     */
    private function isEnLetter() {
        if ($this->currChar == "" || $this->currChar == $this->eof) {
            return false;
        }
        $ord = mb_ord($this->currChar, $this->currEncode);
        if ($ord > ord('a') && $ord < ord('z')) {
            return true;
        }
        return false;
    }
    
    /**
     * @return false|int
     * 是否中文字符
     */
    private function isCnLetter() {
        return preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $this->currChar);
    }
    
    /**
     * @return bool
     * 是否为数字
     */
    private function isNumber() {
        return is_numeric($this->currChar);
    }
    
    /**
     * @return bool
     * 是否是字符串
     */
    private function isStr() {
        return $this->matchCompleteStr();
    }
    
    /**
     * @return string
     * 匹配完整字符串
     */
    private function matchCompleteStr() {
        $char = "";
        if ($this->currChar == "\"") {
            $this->nextChar();
            while ($this->currChar != "\"") {
                if ($this->currChar != "\"") {
                    $char .= $this->currChar;
                }
                $this->nextChar();
            }
            return $char;
        }
        return $char;
    }
    
    /**
     * @return bool
     * 是否是操作符
     */
    private function isOperator() {
        return in_array($this->currChar, $this->operatorList);
    }
    
    /**
     * @return string
     * 匹配中文字符
     */
    private function matchUntilNextCharIsNotCn() {
        $char = "";
        while ($this->isCnLetter()) {
            $char .= $this->currChar;
            $this->nextChar();
        }
        return $char;
    }
    
    /**
     * @return void 获取下一个字符
     * 获取下一个字符
     */
    private function nextChar() {
        $this->currCharPos += 1;
        $this->currChar    = mb_substr($this->input, $this->currCharPos, 1);
        if ($this->currChar == "") {
            $this->currChar = $this->eof;
        }
    }
    
    /**
     * @param string $input
     * @return bool
     * 是否是关键字
     */
    private function isKeyword(string $input) {
        return ($this->keywordList[$input] ?? "") != "";
    }
    
    public function convert(array $tokens) {
        $code = "";
        foreach ($this->lexerIterator($tokens) as $generator) {
            switch ($generator["type"]) {
                case static::KW:
                    $code .= $this->keywordList[$generator["char"]];
                    break;
                case static::VAR:
                    $code .= sprintf("$%s", $generator["char"]);
                    break;
                case static::OPR:
                    $code .= $this->replace($generator["char"]);
                    break;
                case static::INT:
                    $code .= $generator["char"];
                    break;
                case static::STR:
                    $code .= sprintf("\"%s\"", $generator["char"]);
                    break;
                default:
                    $code .= $generator["char"];
            }
        }
        return $code;
    }
    
    private function replace(string $char) {
        return str_replace("+", ".", $char);
    }
    
    /**
     * @param array $tokens
     * @return \Generator
     */
    private function lexerIterator(array $tokens) {
        foreach ($tokens as $index => $token) {
            yield $token;
        }
    }

}

三、如何使用

require __DIR__ . "/vendor/autoload.php";
// 定义一段代码
$code = << 3){
    地址=1;
}否则{
    地址="艾欧尼亚"
}
说话 = ("我"+"爱")+"你";
返回 姓名+年龄;
EOF;
$lexer = new Lexer($code);
// 自定义你的关键字
$kwMap = [
    "如果" => "if", "否则" => "else", "返回" => "return", "否则如果" => "elseif"
];
$lexer->setKeywordList($kwMap);
// 这里是生成的词
$tokens = $lexer->parseInput();
// 将生成的词转成php,当然你也可以尝试用php-parse转ast再转成php,这里只是简单的拼接
var_dump($lexer->convert($tokens));

生成词

[{
    "type": "variable",
    "char": "姓名",
    "pos": 2
}, {
    "type": "operator",
    "char": "=",
    "pos": 2
}, {
    "type": "string",
    "char": "腕豪",
    "pos": 7
}, {
    "type": "operator",
    "char": ";",
    "pos": 8
}, {
    "type": "variable",
    "char": "问候",
    "pos": 13
}, {
    "type": "operator",
    "char": "=",
    "pos": 13
}, {
    "typ e": "string",
    "char": "你好啊",
    "pos": 17
}, {
    "type": "operator",
    "char": ";",
    "pos": 18
}, {
    "type": "variable",
    "char": "地址",
    "pos": 23
}, {
    "type": "operator",
    "char": "=",
    "pos": 23
}, {
    "type": "operator",
    "char": "(",
    "pos": 24
}, {
    "type": "integer",
    "char": "1",
    "pos": 25
}, {
    "type": "operator",
    "char": " +",
    "pos": 26
}, {
    "type": "integer",
    "char": "2",
    "pos": 27
}, {
    "type": "operator",
    "char": ")",
    "pos": 28
}, {
    "type": "operator",
    "char": "*",
    "pos": 30
}, {
    "type": "integer",
    "char": "3",
    "pos": 32
}, {
    "type": "operator",
    "char": ";",
    "pos": 33
}, {
    "type": "keyword",
    "char": "如果",
    "pos": 37
}, {
    "type": "nul l",
    "char": " ",
    "pos": 38
}, {
    "type": "operator",
    "char": "(",
    "pos": 38
}, {
    "type": "variable",
    "char": "地址",
    "pos": 41
}, {
    "type": "operator",
    "char": ">",
    "pos": 42
}, {
    "type": "integer",
    "char": "3",
    "pos": 44
}, {
    "type": "operator",
    "char": ")",
    "pos": 45
}, {
    "type": "operator",
    "char": "{",
    "pos": 46
}, {
    "type": "variable",
    "char": "地址",
    "pos": 55
}, {
    "type": "operator",
    "char": "=",
    "pos": 55
}, {
    "type": "integer",
    "char": "1",
    "pos": 56
}, {
    "type": "operator",
    "char": ";",
    "pos": 57
}, {
    "type": "operator",
    "char": "}",
    "pos": 60
}, {
    "type": "keyword",
    "char": "否则",
    "pos": 62
}, {
    "type": "null",
    "char ": " ",
    "pos": 63
}, {
    "type": "operator",
    "char": "{",
    "pos": 63
}, {
    "type": "variable",
    "char": "地址",
    "pos": 72
}, {
    "type": "operator",
    "char": "=",
    "pos": 72
}, {
    "type": "string",
    "char": "艾欧尼亚",
    "pos": 78
}, {
    "type": "operator",
    "char": ";",
    "pos": 79
}, {
    "type": "operator",
    "char": "}",
    "pos": 82
}, {
    "type": "variable",
    "char": "说话",
    "pos": 87
}, {
    "type": "operator",
    "char": "=",
    "pos": 88
}, {
    "type": "operator",
    "char": "(",
    "pos": 90
}, {
    "type": "string",
    "char": "我",
    "pos": 93
}, {
    "type": "operator",
    "char": "+",
    "pos": 94
}, {
    "type": "string",
    "char": "爱",
    "pos": 97
}, {
    "type": "operator",
    "char": ")",
    "pos": 98
}, {
    "type": "operator",
    "char": "+",
    "pos": 99
}, {
    "type": "string",
    "char": "你",
    "pos": 102
}, {
    "type": "operator",
    "char": ";",
    "pos": 103
}, {
    "type": "keyword",
    "char": "返回",
    "pos": 107
}, {
    "type": "null",
    "char": " ",
    "pos": 108
}, {
    "type": "variable",
    "char": "姓名",
    "pos": 111
}, {
    "typ e": "operator",
    "char": "+",
    "pos": 111
}, {
    "type": "variable",
    "char": "年龄",
    "pos": 114
}, {
    "type": "operator",
    "char": ";",
    "pos": 114
}]

输出:

$姓名="腕豪";$问候="你好啊";$地址=(1.2)*3;if ($地址>3){$地址=1;}else {$地址="艾欧尼亚";}$说话=("我"."爱")."你";return $姓名.$年龄;

能否执行?当然可以。尽管存在少量Bug,但已不再修复。

四、使用场景

有人质疑其用途,但在OA系统中此类功能仍有应用空间。

至此,关于利用PHP实现词法分析器与自定义语言的介绍结束。更多相关PHP词法分析器内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

上一篇
PHP将Session存储至Memcache服务器的配置方法

传统文件式Session在高并发场景下易成为性能瓶颈,将其迁移至内存数据库Memcache可显著提升读取速度。通过修改php.ini或代码内ini_set函数,可将session.save_handler设为memcache并指定服务器地址,重启服务后Session数据将以Key-Value形式存储于Memcache中,从而优化网站响应速度。

下一篇
PHP解析RuoYi框架Token解密详解

本文介绍如何在PHP环境中解析RuoYi-Vue框架生成的JWT Token。由于RuoYi基于Java开发,其Token生成逻辑涉及特定的Header配置与Base64编码的密钥处理。通过引入php-jwt库并调整签名验证参数,可实现对RuoYi Token的有效解密,进而获取用户信息并配合Redis进行状态校验。

相关文章

更多
PHP中十六进制颜色与RGB颜色值互转的方法

本文介绍在PHP中将16进制颜色(如#FFF)转换为RGB数组,以及将RGB字符串转换为16进制颜色的方法。核心逻辑是将16进制每两位转为十进制数值,或反之通过dechex函数拼接。文章提供了两种不同风格的转换代码实现,涵盖3位和6位16进制格式的处理细节。

2025.04.20 999
PHP中精确设置Session过期时间与失效处理方案

本文详解PHP中Session过期时间的配置机制与常见失效问题的解决方案。通过修改php.ini中的session.gc_maxlifetime、session.cookie_lifetime等参数,可精确控制服务端与客户端的Session生命周期。针对无权限修改配置文件或Session无法传递的情况,提供了利用session_id()、调整output_buffering及自定义session_save_path等代码级替代方案,确保Session在不同环境下的稳定运行。

2026.03.22 952
PHP中奖概率算法实现:刮刮卡与大转盘

本文分享一种基于PHP的中奖概率算法,适用于刮刮卡和大转盘等常见抽奖场景。代码包含详细注释,逻辑清晰且易于集成。通过该算法可实现不同奖项的差异化中奖概率控制,帮助开发者快速构建稳定的抽奖业务模块。

2026.04.08 951
PHP中使用Jpgraph类库绘制图表的完整指南

本文介绍如何在PHP环境中配置并使用Jpgraph类库绘制折线图。首先需开启php_gd2.dll扩展并设置include_path路径,随后通过创建Graph对象、设置Scale、实例化LinePlot及调用Stroke方法完成图表输出。

2026.07.01 949
怎么使用PDO在PHP中安全连接SQL Server数据库

使用 PDO 连接 SQL Server 时,核心是正确构造 DSN 并启用加密与信任证书验证。在 PHP 8+环境中,推荐通过安装 sqlsrv 扩展或配置 ODBC 驱动实现安全连接,重点在于设置 TrustServerCertificate = true 以跳过自签名证书的强制校验,同时使用参数化查询防止注入。

2025.12.19 931
PHP中封装FCKeditor编辑器创建与文章编辑功能

本文介绍如何在PHP项目中通过自定义函数整合FCKeditor富文本编辑器。该函数支持根据参数区分新文章发表与旧文章修改两种模式,自动处理数据库查询以回填内容,并配置编辑器尺寸及路径。同时提供了直接嵌入页面的简化实现方式,便于快速在表单中调用编辑器组件。

2025.04.08 885

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。