使用 gettext 扩展配合 xgettext 工具提取,或借助 Composer 包如 symfony/translation-extractor 自动化扫描。

提取硬编码文本的核心方法
PHP 项目中硬编码文本通常包裹在 _() 或 gettext() 函数中。手动查找效率低且易遗漏,推荐使用命令行工具 xgettext 解析 PHP 源码生成 .pot 模板文件。

xgettext 支持递归扫描目录,自动识别 _()、ngettext() 等标准翻译函数调用。执行时需指定语言为 PHP,并输出 UTF-8 编码的 POT 文件。对于复杂项目,可结合正则表达式补充提取未包裹的字符串,但需人工校验上下文准确性。
自动化提取程序实现
以下 Python 脚本演示如何扫描 PHP 文件并提取 _() 包裹的字符串,生成简易 CSV 列表供翻译团队处理。

import os
import re
import csv
def extract_php_strings(directory, output_file):
strings = []
# 匹配 _("...") 或 _('...') 中的内容
pattern = re.compile(r'_\(["\']([^"\']+)["\']\)')
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.php'):
filepath = os.path.join(root, file)
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
matches = pattern.finditer(content)
for match in matches:
line_no = content[:match.start()].count('\n') + 1
strings.append({
'file': filepath,
'line': line_no,
'text': match.group(1)
})
except Exception as e:
print(f'Error reading {filepath}: {e}')
with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=['file', 'line', 'text'])
writer.writeheader()
writer.writerows(strings)
print(f'Extracted {len(strings)} strings to {output_file}')
if __name__ == '__main__':
extract_php_strings('./src', 'translations.csv')
运行脚本后会在当前目录生成 translations.csv,每行包含源文件路径、行号和提取的文本。若输入包含 __('Welcome'),输出将记录该字符串;若为 $var = 'Hi' 则被忽略。修改 directory 参数可指定扫描范围。
脚本遍历指定目录下的所有 .php 文件,使用正则匹配单双引号包裹的文本参数,忽略注释和变量拼接部分。输出包含文件名、行号和原文的 CSV,便于后续导入翻译管理系统。
处理动态拼接与上下文缺失问题
当文本通过变量拼接(如 'Hello ' . $name)时,标准提取器无法捕获完整语义,需引入上下文标记或使用占位符重构代码。
建议将拼接逻辑改为格式化字符串(如 sprintf('Hello %s', $name)),使提取器能识别固定前缀。若无法重构,可在代码中添加 @trans 注释标记,由自定义解析器结合正则提取相邻静态片段,并在翻译文件中备注变量位置。