网站分类
文章归档
统计信息
  • 文章总数:93
  • 页面总数:2
  • 分类总数:10
  • 标签总数:521
  • 评论总数:0
  • 浏览总数:243567
  • 网站运行:4465天
相关文章
标签列表
RSS

php批量替换内容或指定目录下所有文件内容

strtr() 函数转换字符串中特定的字符。

语法
strtr(string,from,to)或者

strtr(string,array)

   $addr=strtr($addr,"","aao");        //第一种调用方法
   $trans=array("hello"=>"hi","hi"=>"hello");      //定义一个转换数组
   echo strtr("hi all, i said hello",$trans);    
   //普通字符串
   echo strtr("hilla warld","ia","eo");
   //数组
   $arr = array("hello" => "hi", "world" => "earth");
   echo strtr("hello world",$arr);
如果 from 和 to 的长度不同,则格式化为最短的长度。

再看一个简单的函数

// +------ 我以前写的一个替换函数

function file_modify($search_contents, $replace_contents, $filename)

{
        $fp = file_get_contents($filename);

        $new_fp = str_replace($search_contents, $replace_contents, $fp);

        file_put_contents($filename, $new_fp);

}
// +------ 用法

file_modify('sdf hjhj', 'sdf_test hjhj_test', 'test10.html');

// 或者直接用这个


preg_replace('|()(^<]+)()|iSU', "${1}" . 替换后的内容 . "$3", $str); 
preg_replace('|()(^<]+)()|iSU', "${1}" . 替换后的内容 . "$3", $str);


上面我所说的所有问题都只会替换一个文件里面的,那么我想替换一个站点所有目录里面文件指定字符,那么我们来看下面这个函数,我们只要运行就可以替换指定目录所所有文件的所有内容,这个还是特别方便的。


<?php     
if (isset($_GET['dir'])){ //设置文件目录     
    $basedir=$_GET['dir'];     
}else{     
    $basedir = '.';     
}   
$auto = 1;     
checkdir($basedir);     

function checkdir($basedir){     
    if ($dh = opendir($basedir)) {     
        while (($file = readdir($dh)) !== false) {     
            if ($file != '.' && $file != '..'){     
                if (!is_dir($basedir."/".$file)) {     
                echo "filename: $basedir/$file ".checkBOM("$basedir/$file")." ";     
                }else{     
                  $dirname = $basedir."/".$file;     
                  checkdir($dirname);     
                }     
            }     
        }     
        closedir($dh);     
    }
 }     

function checkBOM ($filename) {     
    global $auto;     
    $contents = file_get_contents($filename);     
    $charset[1] = substr($contents, 0, 1);     
    $charset[2] = substr($contents, 1, 1);     
    $charset[3] = substr($contents, 2, 1);     
    if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {     
        if ($auto == 1) {     
            $rest = substr($contents, 3);     
            rewrite ($filename, $rest);     
            return ("BOM found, automatically removed._http://www.111com.net/nokia/c6/");     
        } else {     
            return ("BOM found.");     
        }     
    }     
    else return ("BOM Not Found.");     
}     
function rewrite ($filename, $data) {     
    $filenum = fopen($filename, "w");     
    flock($filenum, LOCK_EX);     
    fwrite($filenum, $data);     
    fclose($filenum);     
}     
?>   







分类:PHP 已阅:2886
关键字:php  批量替换  内容  指定目录  strtr  
上一篇:debian ubuntu多系统引导配置文件详解
下一篇:PHP对文件的操作,写入,读取与替换内容
Copyright © 2014-2015 点点看看 保留所有权利 豫ICP备19041083号-1 公安部备案号41010202002818