To replace the content in a string, we only need to use PHP related functions, such as strstr, str_replace, and regular expressions. Then if we want to replace the content of all files in the directory, we need to traverse the directory first, open the file, and then use the functions mentioned above. Replaced. First, let’s look at the most basic
strtr() function to convert specific characters in a string.
Grammar
strtr (string, from, to) or
strtr(string,array)
*/
The code is as follows | Copy code | ||||||||
$trans=array("hello"=>"hi","hi"=>"hello"); //Define a conversion array echo strtr("hilla warld","ia","eo");
//Array echo strtr("hello world",$arr); |
代码如下 | 复制代码 |
preg_replace('|( )(^<]+)( )|iSU', "" . 替换后的内容 . "", $str);
preg_replace('|( )(^<]+)( )|iSU', "" . 替换后的内容 . "", $str);
|
The code is as follows | Copy code |
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); } // +------ Usage file_modify('sdf hjhj', 'sdf_test hjhj_test', 'test10.html'); |
The code is as follows | Copy code |
preg_replace('|( )(^<]+)( )|iSU', "${1}" . Replaced content. " $3", $str);
preg_replace('|()(^<]+)( )|iSU', "${1}" . Replaced content. " $3", $str);
|
All the problems I mentioned above will only replace the characters in one file, so I want to replace the specified characters in the files in all directories of a site, then let’s look at the following function
代码如下 | 复制代码 |
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.hzhuti.com/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); } ?> |
In this way, we can replace all the contents of all files in the specified directory just by running it. This is very convenient.