PHP,替换多个文件中的文本
需求:
需要对两个目录中的文件内容进行查找替换,两个目录查找替换的内容不一样。
实现中注意几点:
(1)函数递归调用,来检索子目录;
(2)函数名可以以参数形式传递;
(3)用?进行非贪婪匹配;
(4)每行匹配查找、整个文件内容匹配查找
<?php
//loopdir('dir1', 'repfile1');
loopdir('dir2', 'repfile2');
function loopdir($dir, $fun){
$dp = opendir($dir);
chdir($dir);
readdir($dp); //排除当前目录 "."
readdir($dp); //排除上层目录 "."
while( $v = readdir($dp) ){
if( is_dir($v) ) loopdir($v, $fun);
else $fun($v);
echo $v."<br>";
}
chdir("..");
}
function repfile1($filename){
$content = file_get_contents($filename);
if( empty($content) ){
echo "can't open file to read: ".$filename;
return ;
}
//加?号是进行非贪婪匹配,以免匹配的块太大
$content = preg_replace('/if \(!validateEmail\((.*?)"Email address is not valid(.*?})/s',
'if (!validateEmail(\\1"Email address is not valid\\2else if (!isNyhEmail(\\1"Can not add NYH email addresses.\\2',
$content);
writenewfile($filename, $content);
}
function repfile4615($filename){
$fpr = fopen($filename, 'r');
if( empty($fpr) ){
echo "can't open file to read: ".$filename;
return ;
}
$newContent = '';
while( $line = fgets($fpr) ){
$line = preg_replace('/^(.*)\$var_kitchen_dishwasher = "kitchen".\$kitchen_ind."_dishwasher";/s',
'\\1$var_kitchen_dishwasher = "kitchen".\$kitchen_ind."_dishwasher";
\\1$var_kitchen_oven = "kitchen".$kitchen_ind."_oven";
\\1$var_kitchen_fridge = "kitchen".$kitchen_ind."_fridge";', $line);
$newContent .= $line;
}
fclose($fpr);
writenewfile($filename, $newContent);
}
function writenewfile($filename, $content){
$fpw = fopen($filename, 'w');
if( empty($fpw) ){
echo "can't open file to write: ".$filename;
return ;
}
fwrite($fpw, $content);
fclose($fpw);
}
?>
相关文档:
最简单的谁都会的调试(是么?):
本来安装php是没问题 也能用了 但是又从书上抄了一些代码来发现不能用, 那就用眼睛仔细的对着书本纠正一下代码哈 肯定是你抄错了 要么是印刷错了
比如 1(yi)跟l(el) 0(ling)跟O(大写o)等
别笑哈 真的有人抄错过 还让我过去帮忙调试 过去我录入进去(他的没保存) 就全对了
言归正传
Q: "为 ......
class A extends father{
function __construct() {
echo "abstract<br>";
parent::base(); //父类方法
&nb ......
第一种方法:
<?php
class Access{
function getConn(){
$conn = @new COM("ADODB.Connection") or die ("ADO连接失败!");
$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath(__IMP ......
PHP本身是有一个多维数组排序的函数的。
bool
array_multisort
( array
$ar1
[, mixed
$arg
[, mixed
$...
[, array
$...
]]] )
下面是手册当中对于array_multisort函数的描述:
array_multisort() 可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。
关联(string ......
<!--
/* Font Definitions */
@font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;
mso-font-alt:SimSun;
mso-font-charset:134;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 135135232 16 0 262145 0;}
@font-face
{font-family:"\@宋体" ......