Просмотр исходного кода

fix: 继续解决option里的两次json encode问题

过卫栋 4 дней назад
Родитель
Сommit
e35105ae36
1 измененных файлов с 33 добавлено и 6 удалено
  1. 33 6
      app/Console/Commands/FixDoubleEncodedOptions.php

+ 33 - 6
app/Console/Commands/FixDoubleEncodedOptions.php

@@ -133,14 +133,25 @@ class FixDoubleEncodedOptions extends Command
 
         // 如果解码后是字符串,说明是双重编码
         if (is_string($decoded)) {
-            $decoded = json_decode($decoded, true);
+            // 先尝试直接解码
+            $secondDecode = json_decode($decoded, true);
+
             if (json_last_error() !== JSON_ERROR_NONE) {
-                return [
-                    'success' => false,
-                    'error' => '二次JSON解码失败: ' . json_last_error_msg(),
-                    'fixed' => null,
-                ];
+                // 解码失败,可能是 LaTeX 中的反斜杠问题(如 \times, \frac 等)
+                // 尝试将单个反斜杠转义为双反斜杠后再解码
+                $escapedDecoded = $this->escapeLatexBackslashes($decoded);
+                $secondDecode = json_decode($escapedDecoded, true);
+
+                if (json_last_error() !== JSON_ERROR_NONE) {
+                    return [
+                        'success' => false,
+                        'error' => '二次JSON解码失败: ' . json_last_error_msg(),
+                        'fixed' => null,
+                    ];
+                }
             }
+
+            $decoded = $secondDecode;
         }
 
         // 验证结果是数组
@@ -161,4 +172,20 @@ class FixDoubleEncodedOptions extends Command
             'fixed' => $fixed,
         ];
     }
+
+    /**
+     * 转义 LaTeX 公式中的反斜杠
+     * 将非 JSON 转义序列的反斜杠转义为双反斜杠
+     */
+    private function escapeLatexBackslashes(string $str): string
+    {
+        // JSON 合法的转义序列: \", \\, \/, \b, \f, \n, \r, \t, \uXXXX
+        // 其他的反斜杠(如 LaTeX 的 \times, \frac, \sqrt 等)需要转义
+
+        // 使用回调函数处理每个反斜杠
+        return preg_replace_callback('/\\\\(?!["\\\\/bfnrt]|u[0-9a-fA-F]{4})/', function ($match) {
+            // 将单个反斜杠替换为双反斜杠
+            return '\\' . $match[0];
+        }, $str);
+    }
 }