讨论数量:
从官方文档找的例子 测了满足目前的需求 感谢各位大佬帮忙解答
public function strip_comments($source) {
$tokens = token_get_all($source);
$ret = "";
foreach ($tokens as $token) {
if (is_string($token)) {
$ret.= $token;
} else {
list($id, $text) = $token;
switch ($id) {
case T_COMMENT:
case T_ML_COMMENT: // we've defined this
case T_DOC_COMMENT: // and this
break;
default:
$ret.= $text;
break;
}
}
}
return trim(str_replace(array('<?','?>'),array('',''),$ret));
}
我猜你大概是需要上国际化吧,我前两周遇到了这个需求。写了个脚本替换
<?php
require __DIR__ . '/vendor/autoload.php';
$start = 2000; #message.key
$zh = [];
$file_names = [];
$not_file_names = [
'./app/Services/MessageService.php'
];
function searchDir($path, &$files)
{
if (is_dir($path)) {
$opendir = opendir($path);
while ($file = readdir($opendir)) {
if ($file != '.' && $file != '..') {
searchDir($path . '/' . $file, $files);
}
}
closedir($opendir);
}
if (!is_dir($path)) {
$files[] = $path;
}
}
function getDir($dir): array
{
$files = array();
searchDir($dir, $files);
return $files;
}
function replaceContent($matches, $content)
{
global $zh;
foreach ($matches[0] as $text) {
global $start;
$key = $start++;
$replace_text = $text;
$replace_args = [];
preg_match_all('/\{([^}]+)\}/', $replace_text, $args_matchs);
foreach ($args_matchs[0] as $index => $args_match) {
$replace_args[$index] = $args_matchs[1][$index];
$replace_text = str_replace($args_match, ":{$index}", $replace_text);
}
$zh[$key] = $replace_text;
$content_replace_text = "__(\"message.{$key}\"";
if ($replace_args) {
$content_replace_text .= ", [";
foreach ($replace_args as $arg_index => $replace_arg) {
if ($arg_index > 0) {
$content_replace_text .= ", ";
}
$content_replace_text .= $replace_arg;
}
$content_replace_text .= "]";
}
$content_replace_text .= ")";
$content = str_replace($text, $content_replace_text, $content);
}
return $content;
}
$file_names = getDir('./app');
foreach ($file_names as $file_name) {
if (in_array($file_name, $not_file_names)) continue;
$content = file_get_contents($file_name);
preg_match_all('/"[^"^\s]*[\x7f-\xff][^"]*"/', $content, $matches1);
$content = replaceContent($matches1, $content);
preg_match_all('/\'[^\'^\s]*[\x7f-\xff][^\']*\'/', $content, $matches2);
$content = replaceContent($matches2, $content);
file_put_contents($file_name, $content);
}
$messages = "";
foreach ($zh as $key => $value) {
$messages .= "'{$key}' => {$value}," . PHP_EOL;
}
file_put_contents('lang-messages.text', $messages);
推荐文章: