我有一个包含多个 .txt 文件的文件夹,名为:
A500_1.txt
A500_2.txt
A700_1.txt
A700_2.txt
A900_1.txt
...
在每个 .txt 文件中都有:
PRXC1_|TB|CCAAO9-RC|9353970324463|24.99
PRXC1_|TB|CFEXK4-RC|9353970294766|84.99
PRXC1_|TB|CFEXK4-RC|9353970294773|84.99
...
我希望你:
如果文件名以 A500 开头_ 将“TB”替换为“MD”
如果文件名以 A700 开头_ 将“TB”替换为“JB”
如果文件名发件人代码以 A900 开头_ 将“TB”替换为“LD”
我编写了这个函数,但它只是在项目的根目录下创建了一个空的 A500_2.TXT 文件并显示:
Warning: file_get_contents(A500_2.TXT): failed to open stream:
我的错误在哪里?
<?php
function processFile( $path ) {
$dir = './test/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
$filename = basename( $file );
if ( ! in_array($file,array(".","..")))
{
//read the entire string
$str = file_get_contents( $file );
// var_dump($str);
// replace something in the file string
if ( strpos( $filename, 'A500_' ) === 0 ) {
$str = str_replace( 'TB', 'MD', $str );
} else if ( strpos( $filename, 'A700_' ) === 0 ) {
$str = str_replace( 'TB', 'JB', $str );
} else if ( strpos( $filename, 'A900_' ) === 0 ) {
$str = str_replace( 'TB', 'LD', $str );
} else {
// Return false if we don't know what to do with this file
return false;
}
//write the entire string
$writeResult = file_put_contents( $file, $str );
//return true after a file is written successfully, or false on failure
return $writeResult >= 0;
}
}
}
if(processFile( './test/' )) echo "good!";
?>
慕哥9229398