PHP汉转英实用工具之遍历文件提取汉字和替换汉字为英文

第一步:

<?php
function sofile($directory) {
$cncc = array();
$files = scandir($directory);
foreach ($files as $file) {
if ($file == '.' || $file == '..') { continue;}
$path = $directory . '/' . $file;
if (is_dir($path)) {
$cncc = array_merge($cncc, sofile($path));
} else {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($extension, array('js', 'css', 'php', 'html'))) { //遍历的文件格式
$content = file_get_contents($path);
preg_match_all('/[\x{4e00}-\x{9fa5}]((\s?)[\x{4e00}-\x{9fa5}])+/u', $content, $matches);
$cncc = array_merge($cncc, $matches[0]);
}
}
}
return $cncc;
}

$chinese = sofile('./html'); //修改遍历的目录比如./html
$chinese = array_unique($chinese); //去重
usort($chinese, function($a, $b) {
return mb_strlen($b) - mb_strlen($a);
}); //排序
$dada = date("Ymd-His");
$find = join("\r\n",$chinese);//整理为文本用于记录
echo join("<br>\r\n",$chinese);//显示为网页
file_put_contents("hanzi.$dada.log","[ $dada ]=>\r\n".$find,FILE_APPEND);//记录
?>

第二步:翻译

用你的方式将一行一段语句或词翻译(可一次性翻译)

然后将原文复制到excel一列(可复制网页或者生成的文件hanzi*.log),译文一列。

再将内容粘贴到记事本redb.txt

第三步:替换

<?php
function arrcn2en($filex) {
$file = fopen($filex,"r");
$datas = array();
while(!feof($file)){
$data = fgetcsv($file,0,"\t");
$datas[$data[0]] = $data[1];
}
fclose($file);
return $datas;
}

function sofile($directory,$reparr) {
$str1 = array_keys($reparr);
$str2 = array_values($reparr);
if(count($str1) != count($str2)) exit("arr@err");
$cncc = array();
$files = scandir($directory);
foreach ($files as $file) {
if ($file == '.' || $file == '..') { continue;}
$path = $directory . '/' . $file;
if (is_dir($path)) {
$cncc = array_merge($cncc, sofile($path,$reparr));
} else {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($extension, array('js', 'css', 'php', 'html'))) {
$content = file_get_contents($path);
$contentnew=str_replace($str1, $str2,$content);
file_put_contents($path,$contentnew);//,FILE_APPEND
}
}
}
return $cncc;
}

$reparr = arrcn2en("redb.txt"); //读取替换数据:一列原中文,一列译文,制表符分开
$chinese = sofile('./html',$reparr);
?>

汉字译英文可以准确提取汉字并批量翻译,然后一步替换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YUJIANYUE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值