Skip to content

Instantly share code, notes, and snippets.

Created July 2, 2013 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5908757 to your computer and use it in GitHub Desktop.
Save anonymous/5908757 to your computer and use it in GitHub Desktop.
/*
* Функция рекурсивно находит файлы в указанной директории. В случае успеха возвращает массив с элементами-путями к файлам, иначе вернёт false.
* @param string $directoryPath — путь к директории
* @param bool $isPHPOnly — при истинном значении выберет только файлы с расширением .php
* @return array|false
*/
public static function getFilesInDir($directoryPath, $isPHPOnly = false){
if (is_dir($directoryPath)){
$path = realpath($directoryPath);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
if ($isPHPOnly){
$objects = new RegexIterator($objects, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);
}
$arFiles = array();
foreach ($objects as $name => $item){
$arFiles[] = $name;
}
return $arFiles;
}
else{
return false;
}
}
/*
* Функция заменяет строки в искомом файле
* @param string $search — искомая строка
* @param string $replace — строка для замены
* @param string $filePath — путь к файлу
* @return int|false
*/
public static function replaceInFile($search, $replace, $filePath){
if (is_file($filePath)){
$fileContent = file_get_contents($filePath);
$processedContent = str_replace($search, $replace, $fileContent);
return file_put_contents($filePath, $processedContent);
}
else{
return false;
}
}
/*
* Функция заменяет строки в содержимом файлов в директории.
* @param string $search — искомая строка
* @param string $replace — строка для замены
* @param string $directoryPath — путь к директории
* @param bool $isPHPOnly — при истинном значении будет заменено содержимое только .php-файлов
* @return array|bool
*/
public static function replaceInDirectory($search, $replace, $directoryPath, $isPHPOnly = false){
if (is_dir($directoryPath)){
if ($isPHPOnly){
$filesInDirectory = CDeveloperTools::getFilesInDir($directoryPath, $isPHPOnly);
}
else{
$filesInDirectory = CDeveloperTools::getFilesInDir($directoryPath);
}
$arResult = array();
foreach($filesInDirectory as $filePath){
$arResult[$filePath] = CDeveloperTools::replaceInFile($search, $replace, $filePath);
}
return $arResult;
}
else{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment