Snippets

Alexey ilyaskin Исправление кодировки имен файлов в Windows

Created by Alexey ilyaskin
<?php
/*
 * Исправление кодировки имен файлов в Windows после распаковки архива, созданного в Linux.
 * Исправляются имена всех файлов, расположенных в данной директории и всех ее поддиректориях.
 */

processDir(__DIR__);



function processDir($target) {
	$target = fixPath($target);
	$dir = opendir($target);
	while (false !== ($file = readdir($dir))) {
		if ($file == '.' || $file == '..') {
			continue;
		}
		$newFileName = fixCharset($file);
		rename($target . '/' . $file, $target . '/' . $newFileName);
		$path = $target . '/' . $newFileName;
		if (is_dir($path)) {
			processDir($path);
		}
	}
	closedir($dir);
}

function fixPath($path) {
	return rtrim(str_replace('\\', '/', $path), '/');
}

function fixCharset($fileName) {
	if (mb_detect_encoding($fileName, 'UTF-8', true) == 'UTF-8') {
		return iconv('UTF-8', 'Windows-1251//IGNORE', $fileName);
	}
	return $fileName;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.