찾다
백엔드 개발PHP 튜토리얼写了个遍历目录、批量替换文件内容的类解决思路

写了个遍历目录、批量替换文件内容的类
之前有需要,就写了这个类。
功能:
1 遍历目录下的所有文件(可指定后缀名)
2 批量替换文件内容(正则、字符串)
3 批量替换文件后缀名
4 批量替换文件编码

使用例:

PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->$dirExplorer = new DirExplorerClass();$dirExplorer->getDirExplorer('D:/test1/test2/');                                  //遍历目录D:/test1/test2/$dirExplorer->modifyFileBy_replace('aa','QQ','shift-jis','UTF-8','txt','TXT');    //将所有文件内容中的aa替换为QQ,文件编码从shift-jis转换为UTF-8,将所有txt的后缀名改为TXT


类代码:
PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->class DirExplorerClass{    var $dirPath_array = array();//遍历文件结果集合    function __construct(){        //donothing    }    /*    *  return a directory handle or die        */    private function openDir($dirPath_target) {        if (is_dir($dirPath_target)) {            return opendir($dirPath_target);        }else {            die("$dirPath_target is Not a Directory");        }    }    /*    *  close a directory handle        */    private function closeDir($dirHander) {        closedir($dirHander);    }    /*    *  遍历指定目录,返回其下的文件名集合    *    *  Parameters:    *      1 dirPath:需要遍历的文件夹    *      2 extension:只返回指定后缀名的文件     *  Return:    *      遍历文件结果集合        */    function getDirExplorer($dirPath,$extension=''){        $dirHander=$this->openDir($dirPath);        while($fileName = readdir($dirHander)){            if($fileName !='.' && $fileName !='..'){                $path = $dirPath."/" . $fileName;                if(is_dir($path)){                    $this->getDirExplorer($path);                }else{                    if(isset($extension) && $extension != ''){                        $fileExtension = end(explode('.',$fileName));                        if($fileExtension != $extension){                            continue;                        }                    }                    $this->dirPath_array[]=$path;                }            }        }        $this->closeDir($dirHander);        return $this->dirPath_array;    }    /*    *  字符串替换文件内容(区别大小写)、编码、后缀名    *    *  Parameters:    *      1 search:    需要替换的字符串 (数组可)    *      2 replace:    替换后的字符串 (数组可)    *      3 in_charset:    原编码    *      4 out_charset:    新编码    *      5 in_extension:    原后缀名    *      6 out_extension:新后缀名    *  Return:    *      true or false        */    function modifyFileBy_replace($search, $replace, $in_charset='', $out_charset='', $in_extension='', $out_extension=''){        /* input check */        if(            !isset($search) || !isset($replace) ||             (strlen($in_charset)!=0 && strlen($in_charset)==0)  || (strlen($in_charset)==0 && strlen($in_charset)!=0) ||            (strlen($in_extension)!=0 && strlen($out_extension)==0)  || (strlen($in_extension)==0 && strlen($out_extension)!=0)        ){            return false;        }        foreach($this->dirPath_array as $key=>$file) {            $content = file_get_contents($file);//read contents            $content = str_replace($search, $replace, $content);            if(strlen($in_charset)!=0 && strlen($out_charset)!=0){                /* change the encode */                $this->changeCharset($in_charset, $out_charset, 1, $content);            }            unlink($file);            if(strlen($in_extension)!=0 && strlen($out_extension)!=0){                /* change file's extension */                $this->changeExtension($in_extension, $out_extension, 1, $file);            }            file_put_contents($file, $content);            unset($content);            /* 更新遍历文件名结果集 */            $this->dirPath_array[$key] = $file;        }        return true;    }    /*    *  字符串替换文件内容(忽略大小写)、编码、后缀名        */    function modifyFileBy_ireplace($search, $replace, $in_charset='', $out_charset='', $in_extension='', $out_extension=''){        //不贴了 和上面的modifyFileBy_replace一样 只是用str_ireplace替换而已    }    /*    *  正则替换文件内容(忽略大小写)、编码、后缀名    *    *  Parameters:    *      1 search:    需要替换内容的正则表达式    *      2 replace:    替换后的字符串    *      3 in_charset:    原编码    *      4 out_charset:    新编码    *      5 in_extension:    原后缀名    *      6 out_extension:新后缀名    *  Return:    *      true or false        */    function modifyFileBy_regex($search, $replace, $in_charset='', $out_charset='', $in_extension='', $out_extension=''){        /* input check */        if(            !isset($search) || !isset($replace) ||             (strlen($in_charset)!=0 && strlen($in_charset)==0)  || (strlen($in_charset)==0 && strlen($in_charset)!=0) ||            (strlen($in_extension)!=0 && strlen($out_extension)==0)  || (strlen($in_extension)==0 && strlen($out_extension)!=0)        ){            return false;        }        if(preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) {            /* remove eval-modifier from $search */            $search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]);        }        foreach($this->dirPath_array as $key=>$file) {            $content = file_get_contents($file);//read contents            $content = preg_replace($search, $replace, $content);            if(strlen($in_charset)!=0 && strlen($out_charset)!=0){                /* change the encode */                $this->changeCharset($in_charset, $out_charset, 1, $content);            }            unlink($file);            if(strlen($in_extension)!=0 && strlen($out_extension)!=0){                /* change file's extension */                $this->changeExtension($in_extension, $out_extension, 1, $file);            }            file_put_contents($file, $content);            unset($content);            /* 更新遍历文件名结果集 */            $this->dirPath_array[$key] = $file;        }        return true;    }    /*    *  变换编码    *    *  Parameters:    *      1 in_charset:    原编码    *      2 out_charset:    新编码    *      3 flag:        0对遍历得到的文件转换编码 1对指定内容转换编码    *      4 content:    仅在flag为1时使用    *  Return:    *      true or false        */    function changeCharset($in_charset='', $out_charset='', $flag=0, &$content=''){        /* input check */        if (strlen($in_charset)==0 || strlen($out_charset)==0){            return false;        }        if($flag == 0){            /* 对遍历得到的文件转换编码 */            foreach($this->dirPath_array as $file) {                $content = file_get_contents($file);//read contents                /* change the encode */                $content = iconv($in_charset, $out_charset, $content);                unlink($file);                file_put_contents($file, $content);                unset($content);            }        }else{            /* 对指定内容转换编码 */            if(strlen($content) != 0){                $content = iconv($in_charset, $out_charset, $content);            }        }        return true;    }    /*    *  变换后缀名    *    *  Parameters:    *      1 in_extension:        原后缀名    *      2 out_extension:    新后缀名    *      3 flag:            0对遍历得到的文件变换后缀名 1对指定文件名变换后缀名    *      4 fileName:        仅在flag为1时使用    *  Return:    *      true or false        */    function changeExtension($in_extension='', $out_extension='', $flag=0, &$fileName=''){        /* inout check */        if(strlen($in_extension)==0 || strlen($out_extension)==0){            return false;        }        if($flag == 0){            /* 对遍历得到的文件变换后缀名 */            foreach($this->dirPath_array as $key=>$file) {                /* change file's extension */                $tmp = explode('.',$file);                $nowExtension = array_pop($tmp);                if($nowExtension == $in_extension){                    $content = file_get_contents($file);//read contents                    unlink($file);                    $file = implode('.',$tmp).'.'.$out_extension;                    file_put_contents($file, $content);                    unset($content);                }                /* 更新遍历文件名结果集 */                $this->dirPath_array[$key] = $file;            }        }else{            /* 对指定文件名变换后缀名 */            if(strlen($fileName) != 0){                $tmp = explode('.',$fileName);                $nowExtension = array_pop($tmp);                if($nowExtension == $in_extension){                    $fileName = implode('.',$tmp).'.'.$out_extension;                }            }        }        return true;    }}<div class="clear">
                 
              
              
        
            </div>
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
과대 광고 : 오늘 PHP의 역할을 평가합니다과대 광고 : 오늘 PHP의 역할을 평가합니다Apr 12, 2025 am 12:17 AM

PHP는 현대적인 프로그래밍, 특히 웹 개발 분야에서 강력하고 널리 사용되는 도구로 남아 있습니다. 1) PHP는 사용하기 쉽고 데이터베이스와 완벽하게 통합되며 많은 개발자에게 가장 먼저 선택됩니다. 2) 동적 컨텐츠 생성 및 객체 지향 프로그래밍을 지원하여 웹 사이트를 신속하게 작성하고 유지 관리하는 데 적합합니다. 3) 데이터베이스 쿼리를 캐싱하고 최적화함으로써 PHP의 성능을 향상시킬 수 있으며, 광범위한 커뮤니티와 풍부한 생태계는 오늘날의 기술 스택에 여전히 중요합니다.

PHP의 약한 참고 자료는 무엇이며 언제 유용합니까?PHP의 약한 참고 자료는 무엇이며 언제 유용합니까?Apr 12, 2025 am 12:13 AM

PHP에서는 약한 참조가 약한 회의 클래스를 통해 구현되며 쓰레기 수집가가 물체를 되 찾는 것을 방해하지 않습니다. 약한 참조는 캐싱 시스템 및 이벤트 리스너와 같은 시나리오에 적합합니다. 물체의 생존을 보장 할 수 없으며 쓰레기 수집이 지연 될 수 있음에 주목해야합니다.

PHP의 __invoke 마법 방법을 설명하십시오.PHP의 __invoke 마법 방법을 설명하십시오.Apr 12, 2025 am 12:07 AM

\ _ \ _ 호출 메소드를 사용하면 객체를 함수처럼 호출 할 수 있습니다. 1. 객체를 호출 할 수 있도록 메소드를 호출하는 \ _ \ _ 정의하십시오. 2. $ obj (...) 구문을 사용할 때 PHP는 \ _ \ _ invoke 메소드를 실행합니다. 3. 로깅 및 계산기, 코드 유연성 및 가독성 향상과 같은 시나리오에 적합합니다.

동시성에 대해 PHP 8.1의 섬유를 설명하십시오.동시성에 대해 PHP 8.1의 섬유를 설명하십시오.Apr 12, 2025 am 12:05 AM

섬유는 PHP8.1에 도입되어 동시 처리 기능을 향상시켰다. 1) 섬유는 코 루틴과 유사한 가벼운 동시성 모델입니다. 2) 개발자는 작업의 실행 흐름을 수동으로 제어 할 수 있으며 I/O 집약적 작업을 처리하는 데 적합합니다. 3) 섬유를 사용하면보다 효율적이고 반응이 좋은 코드를 작성할 수 있습니다.

PHP 커뮤니티 : 자원, 지원 및 개발PHP 커뮤니티 : 자원, 지원 및 개발Apr 12, 2025 am 12:04 AM

PHP 커뮤니티는 개발자 성장을 돕기 위해 풍부한 자원과 지원을 제공합니다. 1) 자료에는 공식 문서, 튜토리얼, 블로그 및 Laravel 및 Symfony와 같은 오픈 소스 프로젝트가 포함됩니다. 2) 지원은 StackoverFlow, Reddit 및 Slack 채널을 통해 얻을 수 있습니다. 3) RFC에 따라 개발 동향을 배울 수 있습니다. 4) 적극적인 참여, 코드에 대한 기여 및 학습 공유를 통해 커뮤니티에 통합 될 수 있습니다.

PHP vs. Python : 차이점 이해PHP vs. Python : 차이점 이해Apr 11, 2025 am 12:15 AM

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP : 죽어 가거나 단순히 적응하고 있습니까?PHP : 죽어 가거나 단순히 적응하고 있습니까?Apr 11, 2025 am 12:13 AM

PHP는 죽지 않고 끊임없이 적응하고 진화합니다. 1) PHP는 1994 년부터 새로운 기술 트렌드에 적응하기 위해 여러 버전 반복을 겪었습니다. 2) 현재 전자 상거래, 컨텐츠 관리 시스템 및 기타 분야에서 널리 사용됩니다. 3) PHP8은 성능과 현대화를 개선하기 위해 JIT 컴파일러 및 기타 기능을 소개합니다. 4) Opcache를 사용하고 PSR-12 표준을 따라 성능 및 코드 품질을 최적화하십시오.

PHP의 미래 : 적응 및 혁신PHP의 미래 : 적응 및 혁신Apr 11, 2025 am 12:01 AM

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전