백엔드 개발 PHP 튜토리얼 搜索和替换文件或目录的一个好类--很实用

搜索和替换文件或目录的一个好类--很实用

Jun 01, 2016 pm 02:30 PM

这是个非常有用的程序,可以对文本文件进行特定的搜索,并以特定的文字替换指定的文字,举个例子说如果我这篇文章里有一个字全部打错了,有几十处,要一一找出来修改是件很麻烦的事,用下面这个就可以轻松搞定。--teaman.oso.com.cn
类文件 search_replace.inc


    class search_replace{

        var $find;
        var $replace;
        var $files;
        var $directories;
        var $include_subdir;
        var $ignore_lines;
        var $ignore_sep;
        var $occurences;
        var $search_function;
        var $last_error;

    //以下进行函数定义和设置
     
        function search_replace($find, $replace, $files, $directories = '', $include_subdir = 1, $ignore_lines = array()){

            $this->find      = $find;
            $this->replace     = $replace;
            $this->files      = $files;
            $this->directories   = $directories;
            $this->include_subdir = $include_subdir;
            $this->ignore_lines  = $ignore_lines;

            $this->occurences   = 0;
            $this->search_function = 'search';
            $this->last_error   = '';

        }

    /***************************************
    ** accessor for retrieving occurences.
    ***************************************/
        function get_num_occurences(){
            return $this->occurences;
        }

    //获取最后的错误
        function get_last_error(){
            return $this->last_error;
        }

    //设置FIND变量
        function set_find($find){
            $this->find = $find;
        }

    //设置replace变量
        function set_replace($replace){
            $this->replace = $replace;
        }

    //设置FILE变量
        function set_files($files){
            $this->files = $files;
        }

    //设置目录变量
        function set_directories($directories){
            $this->directories = $directories;
        }

    //设置目录变量 set_include_subdir
        function set_include_subdir($include_subdir){
            $this->include_subdir = $include_subdir;
        }

    //设置ignore_lines变量
        function set_ignore_lines($ignore_lines){
            $this->ignore_lines = $ignore_lines;
        }

    //确定是哪一种搜索方式
        function set_search_function($search_function){
            switch($search_function){
                case 'normal': $this->search_function = 'search';
                        return TRUE;
                        break;

                case 'quick' : $this->search_function = 'quick_search';
                        return TRUE;
                        break;

                case 'PReg' : $this->search_function = 'preg_search';
                        return TRUE;
                        break;

                case 'ereg' : $this->search_function = 'ereg_search';
                        return TRUE;
                        break;

                default   : $this->last_error   = 'Invalid search function specified';
                        return FALSE;
                        break;
            }
        }


    //以下为搜索和替换程序的主文件
        function search($filename){

            $occurences = 0;
            $file_array = file($filename);

            for($i=0; $i                 $continue_flag = 0;
                if(count($this->ignore_lines) > 0){
                    for($j=0; $jignore_lines); $j++){
                        if(substr($file_array[$i],0,strlen($this->ignore_lines[$j])) == $this->ignore_lines[$j]) $continue_flag = 1;
                    }
                }
                if($continue_flag == 1) continue;
                $occurences += count(explode($this->find, $file_array[$i])) - 1;
                $file_array[$i] = str_replace($this->find, $this->replace, $file_array[$i]);
            }
            if($occurences > 0) $return = array($occurences, implode('', $file_array)); else $return = FALSE;
            return $return;

        }

    //使用quick(快速)搜索方法时,没有igonre_lines功能
        function quick_search($filename){

            clearstatcache();

            $file    = fread($fp = fopen($filename, 'r'), filesize($filename)); fclose($fp);
            $occurences = count(explode($this->find, $file)) - 1;
            $file    = str_replace($this->find, $this->replace, $file);

            if($occurences > 0) $return = array($occurences, $file); else $return = FALSE;
            return $return;

        }

    //preg搜索方法不支持ignore_lines
        function preg_search($filename){

            clearstatcache();

            $file    = fread($fp = fopen($filename, 'r'), filesize($filename)); fclose($fp);
            $occurences = count($matches = preg_split($this->find, $file)) - 1;
            $file    = preg_replace($this->find, $this->replace, $file);

            if($occurences > 0) $return = array($occurences, $file); else $return = FALSE;
            return $return;

        }

    //ereg搜索方法也不支持ignore_lines
        function ereg_search($filename){

            clearstatcache();

            $file = fread($fp = fopen($filename, 'r'), filesize($filename)); fclose($fp);

            $occurences = count($matches = split($this->find, $file)) -1;
            $file    = ereg_replace($this->find, $this->replace, $file);

            if($occurences > 0) $return = array($occurences, $file); else $return = FALSE;
            return $return;

        }

    //写新文件
        function writeout($filename, $contents){

            if($fp = @fopen($filename, 'w')){
                fwrite($fp, $contents);
                fclose($fp);
            }else{
                $this->last_error = 'Could not open file: '.$filename;
            }

        }

    //由do_search调用,排出所有要搜索的文件
        function do_files($ser_func){
            if(!is_array($this->files)) $this->files = explode(',', $this->files);
            for($i=0; $ifiles); $i++){
                if($this->files[$i] == '.' OR $this->files[$i] == '..') continue;
                if(is_dir($this->files[$i]) == TRUE) continue;
                $newfile = $this->$ser_func($this->files[$i]);
                if(is_array($newfile) == TRUE){
                    $this->writeout($this->files[$i], $newfile[1]);
                    $this->occurences += $newfile[0];
                }
            }
        }

    //由do_search()调用,排出所有要搜索的目录
        function do_directories($ser_func){
            if(!is_array($this->directories)) $this->directories = explode(',', $this->directories);
            for($i=0; $idirectories); $i++){
                $dh = opendir($this->directories[$i]);
                while($file = readdir($dh)){
                    if($file == '.' OR $file == '..') continue;

                    if(is_dir($this->directories[$i].$file) == TRUE){
                        if($this->include_subdir == 1){
                            $this->directories[] = $this->directories[$i].$file.'/';
                            continue;
                        }else{
                            continue;
                        }
                    }

                    $newfile = $this->$ser_func($this->directories[$i].$file);
                    if(is_array($newfile) == TRUE){
                        $this->writeout($this->directories[$i].$file, $newfile[1]);
                        $this->occurences += $newfile[0];
                    }
                }
            }
        }

    //调用这个do_search()就可以开始对文件或目录进行搜索
        function do_search(){
            if($this->find != ''){
                if((is_array($this->files) AND count($this->files) > 0) OR $this->files != '') $this->do_files($this->search_function);
                if($this->directories != '')                    $this->do_directories($this->search_function);
            }
        }

    } // End of class
?>

//下面是调用该类的例子说明,请存为example.php


    include('search_replace.inc'); //将文件包括进来

//建立新物件,设置搜索条件、最后返回搜索结果

    $sr = new search_replace('asp', 'php', array('test.txt')); //调用搜索与替换
    $sr->set_search_function('quick');  //设置搜索条件
    $sr->do_search();

    $sr->set_find('another');
    $sr->do_search();

//下面是定制的返回信息
    header('Content-Type: text/plain');
    echo '发现和替换以下几个地方: '.$sr->get_num_occurences()."\r\n";
    echo '啊,错误发生如下.............: '.$sr->get_last_error()."\r\n";
?>

//将以下文字存为test.txt,注意text.txt必须是可读可写的
"我非常喜欢asp,它简单易学,功能强,听说asp已经占了大半市场,asp真好。"

此时,如果您打开exampe.php 就会出现下面这些:
发现和替换以下几个地方:3
啊,错误发生如下..........:   
查看test.txt文件,果然出现asp的地方被php替换了。
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
<exp exp> 모호한 : 원정 33- 완벽한 크로마 촉매를 얻는 방법
2 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP에서 보안 비밀번호 해싱을 설명하십시오 (예 : Password_hash, Password_Verify). 왜 MD5 또는 SHA1을 사용하지 않습니까? PHP에서 보안 비밀번호 해싱을 설명하십시오 (예 : Password_hash, Password_Verify). 왜 MD5 또는 SHA1을 사용하지 않습니까? Apr 17, 2025 am 12:06 AM

PHP에서 Password_hash 및 Password_Verify 기능을 사용하여 보안 비밀번호 해싱을 구현해야하며 MD5 또는 SHA1을 사용해서는 안됩니다. 1) Password_hash는 보안을 향상시키기 위해 소금 값이 포함 된 해시를 생성합니다. 2) Password_verify 암호를 확인하고 해시 값을 비교하여 보안을 보장합니다. 3) MD5 및 SHA1은 취약하고 소금 값이 부족하며 현대 암호 보안에는 적합하지 않습니다.

스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까? 스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까? Apr 17, 2025 am 12:25 AM

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP와 Python : 다른 패러다임이 설명되었습니다 PHP와 Python : 다른 패러다임이 설명되었습니다 Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python 중에서 선택 : 가이드 PHP와 Python 중에서 선택 : 가이드 Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP와 Python : 그들의 역사에 깊은 다이빙 PHP와 Python : 그들의 역사에 깊은 다이빙 Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

PHP 및 프레임 워크 : 언어 현대화 PHP 및 프레임 워크 : 언어 현대화 Apr 18, 2025 am 12:14 AM

PHP는 현대화 프로세스에서 많은 웹 사이트 및 응용 프로그램을 지원하고 프레임 워크를 통해 개발 요구에 적응하기 때문에 여전히 중요합니다. 1.PHP7은 성능을 향상시키고 새로운 기능을 소개합니다. 2. Laravel, Symfony 및 Codeigniter와 같은 현대 프레임 워크는 개발을 단순화하고 코드 품질을 향상시킵니다. 3. 성능 최적화 및 모범 사례는 응용 프로그램 효율성을 더욱 향상시킵니다.

PHP를 사용하는 이유는 무엇입니까? 설명 된 장점과 혜택 PHP를 사용하는 이유는 무엇입니까? 설명 된 장점과 혜택 Apr 16, 2025 am 12:16 AM

PHP의 핵심 이점에는 학습 용이성, 강력한 웹 개발 지원, 풍부한 라이브러리 및 프레임 워크, 고성능 및 확장 성, 크로스 플랫폼 호환성 및 비용 효율성이 포함됩니다. 1) 배우고 사용하기 쉽고 초보자에게 적합합니다. 2) 웹 서버와 우수한 통합 및 여러 데이터베이스를 지원합니다. 3) Laravel과 같은 강력한 프레임 워크가 있습니다. 4) 최적화를 통해 고성능을 달성 할 수 있습니다. 5) 여러 운영 체제 지원; 6) 개발 비용을 줄이기위한 오픈 소스.

PHP의 영향 : 웹 개발 및 그 이상 PHP의 영향 : 웹 개발 및 그 이상 Apr 18, 2025 am 12:10 AM

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

See all articles