php批量替換內容或指定目錄下所有文件內容
來源:程序員人生 發(fā)布時間:2013-11-01 01:21:36 閱讀次數(shù):3191次
要替換字符串中的內容我們只要利用php相關函數(shù),如strstr,str_replace,正則表達式了,那么我們要替換目錄所有文件的內容就需要先遍歷目錄再打開文件再利用上面講的函數(shù)替換了,我們先看最基本的.
strtr() 函數(shù)轉換字符串中特定的字符。
語法: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 的長度不同,則格式化為最短的長度,再看一個簡單的函數(shù),代碼如下:
- 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('|(<div class="body">)(^<]+)(</div>)|iSU', "${1}" . 替換后的內容 . "$3", $str);
上面我所說的所有問題都只會替換一個文件里面的,那么我想替換一個站點所有目錄里面文件指定字符,那么我們來看下面這個函數(shù),代碼如下:
- <?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")." <br>";
- }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 ("<font color=red>BOM found, automatically removed._<a href=http://www.phpfensi.com>http://www.phpfensi.com/nokia/c6/</a></font>");
- } else {
- return ("<font color=red>BOM found.</font>");
- }
- }
- else return ("BOM Not Found.");
- }
- function rewrite ($filename, $data) {
- $filenum = fopen($filename, "w");
- flock($filenum, LOCK_EX);
- fwrite($filenum, $data);
- fclose($filenum);
- }
- ?>
這樣我們只要運行就可以替換指定目錄所所有文件的所有內容,這個還是特別方便的。
生活不易,碼農辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈