php递归提取目录中所有的汉字
直接上代码:
<?php function extractChineseText($directory) { $chineseText = []; // 遍历目录下的所有文件和子目录 $files = scandir($directory); foreach ($files as $file) { if ($file === '.' || $file === '..') { continue; } $filePath = $directory . DIRECTORY_SEPARATOR . $file; // 如果是目录,递归调用本函数 if (is_dir($filePath)) { $chineseText = array_merge($chineseText, extractChineseText($filePath)); } // 如果是文件,提取中文内容 elseif (is_file($filePath)) { $content = file_get_contents($filePath); // 使用正则表达式排除注释 $content = preg_replace('~/\*.*?\*/~s', '', $content); $content = preg_replace('~//.*$~m', '', $content); preg_match_all('/[\x{4e00}-\x{9fa5},::,]+/u', $content, $matches); $chineseText = array_merge($chineseText, $matches[0]); } } return $chineseText; } // 调用函数,传入要搜索的目录 $directory = 'F:\WWW\askme\app\tool\\'; $chineseText = extractChineseText($directory); $chineseText = array_unique(array_filter($chineseText)); foreach ($chineseText as $item) { if (mb_strlen($item) > 1) { $new[] = $item; } } file_put_contents('trans.txt', implode(PHP_EOL, $new)); // 展示结果 var_dump($new);