Parcourir la source

fix: solution里大括号问题

过卫栋 il y a 4 semaines
Parent
commit
c90dc9a3c4
1 fichiers modifiés avec 20 ajouts et 16 suppressions
  1. 20 16
      app/Services/MathFormulaProcessor.php

+ 20 - 16
app/Services/MathFormulaProcessor.php

@@ -73,33 +73,37 @@ class MathFormulaProcessor
     }
 
     /**
-     * 【新增】将公式定界符内的双反斜杠转为单反斜杠
-     * 与前端 MathText.tsx 的 preprocessText 逻辑保持一致
+     * 【新增】将公式定界符内被JSON双重转义的LaTeX命令还原
+     * 例如:\\sqrt -> \sqrt, \\frac -> \frac
+     * 但保留矩阵换行符 \\ (后面不跟字母的情况)
      */
     private static function normalizeBackslashesInDelimiters(string $content): string
     {
-        // 1. 处理 $$...$$ 块级公式内的双反斜杠
-        $content = preg_replace_callback('/\$\$([\s\S]*?)\$\$/', function ($matches) {
-            $tex = str_replace('\\\\', '\\', $matches[1]);
-            return '$$' . $tex . '$$';
+        // 只替换 \\+字母 的情况(被JSON转义的LaTeX命令)
+        // 保留 \\+数字 或 \\+空白 的情况(矩阵换行符)
+        $fixEscapedCommands = function ($tex) {
+            // \\sqrt -> \sqrt, \\frac -> \frac, 但 \\2 或 \\ 保持不变
+            return preg_replace('/\\\\\\\\([a-zA-Z])/', '\\\\$1', $tex);
+        };
+
+        // 1. 处理 $$...$$ 块级公式
+        $content = preg_replace_callback('/\$\$([\s\S]*?)\$\$/', function ($matches) use ($fixEscapedCommands) {
+            return '$$' . $fixEscapedCommands($matches[1]) . '$$';
         }, $content);
 
-        // 2. 处理 $...$ 行内公式内的双反斜杠(避免与$$冲突)
-        $content = preg_replace_callback('/(?<!\$)\$([^$\n]+?)\$(?!\$)/', function ($matches) {
-            $tex = str_replace('\\\\', '\\', $matches[1]);
-            return '$' . $tex . '$';
+        // 2. 处理 $...$ 行内公式(避免与$$冲突)
+        $content = preg_replace_callback('/(?<!\$)\$([^$\n]+?)\$(?!\$)/', function ($matches) use ($fixEscapedCommands) {
+            return '$' . $fixEscapedCommands($matches[1]) . '$';
         }, $content);
 
         // 3. 处理 \(...\) 行内公式
-        $content = preg_replace_callback('/\\\\\(([\s\S]*?)\\\\\)/', function ($matches) {
-            $tex = str_replace('\\\\', '\\', $matches[1]);
-            return '\\(' . $tex . '\\)';
+        $content = preg_replace_callback('/\\\\\(([\s\S]*?)\\\\\)/', function ($matches) use ($fixEscapedCommands) {
+            return '\\(' . $fixEscapedCommands($matches[1]) . '\\)';
         }, $content);
 
         // 4. 处理 \[...\] 块级公式
-        $content = preg_replace_callback('/\\\\\[([\s\S]*?)\\\\\]/', function ($matches) {
-            $tex = str_replace('\\\\', '\\', $matches[1]);
-            return '\\[' . $tex . '\\]';
+        $content = preg_replace_callback('/\\\\\[([\s\S]*?)\\\\\]/', function ($matches) use ($fixEscapedCommands) {
+            return '\\[' . $fixEscapedCommands($matches[1]) . '\\]';
         }, $content);
 
         return $content;