利用php,js等语言便捷的字符串处理能力,在整理老项目语言包时候,可以使用脚本程序读取文件每行,匹配中文,然后以自己想要的形式输出.
<?php
//中文 正则表达式匹配
$cn_pattern = "/([\x{4e00}-\x{9fa5}]+)/u";
//待检测代码后缀
$suffix = 'php';
$dir_path = '/Users/away/workspace/svn/nis/web/application/views/page';
//忽略含有关键词的文件名
$ignore_file_keywords = [];
// $suffix = 'js';
// $dir_path = '/Users/away/workspace/svn/nis/web/static';
// $ignore_file_keywords = ['jquery', 'echart', 'liquidFill', 'plugins', 'laydate'];
//获取文件列表
get_files_path($dir_path);
foreach ($file_list as $file)
{
search_file($file);
}
//遍历获取文件路径
function get_files_path($dir) {
global $file_list,$suffix, $ignore_file_keywords;
$suffix_len = strlen($suffix);
$files = array();
if(@$handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != ".." && $file != ".") {
$ignore = false;
foreach ($ignore_file_keywords as $keyword) {
if (strstr($file, $keyword)) {
$ignore = true;
break;
}
}
if ($ignore) continue;
if (is_dir($dir."/".$file)) {
get_files_path($dir."/".$file);
} else {
if(substr($file, -$suffix_len) == $suffix){
$file_list[] = $dir."/".$file;
}
}
}
}
closedir($handle);
return;
}
}
//搜索单个文件,查找中文
function search_file($file_path){
global $cn_pattern;
$file = fopen($file_path, 'r');
if (empty($file)) return;
$line_index = 0;
while (!feof($file)) {
$line_index++;
$line = fgets($file);
preg_match_all($cn_pattern, $line, $matches);
if (empty($matches[0])) continue;
foreach ($matches[1] as $string) {
// if (strstr($line, "//")) continue;
// if (strstr($line, "<!--")) continue;
echo "[path:line]\t",$file_path,":{$line_index}\n";
echo "[content:]\t",trim($line), "\n";
echo "[string:]\t",$string, "\n\n";
}
}
fclose($file);
}
命令行用php执行该脚本,
php /path/run.php
输出结果如下: