在PHP中查找和替换多个文本文件中的字符串

时间:2011-10-18 11:51:45

标签: php

我找到了这段代码:

<?php
$path_to_file = 'c:\wamp\www\FindReplace\File.txt';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("Paul",",HHH",$file_contents);
file_put_contents($path_to_file,$file_contents);
?>

如果它只有一个文件但是如果我想在我的文件夹的所有* .txt文件中查找和替换该怎么办?

感谢你

3 个答案:

答案 0 :(得分:2)

这个怎么样? 它应该注意在所有.txt文件上运行替换,无论你在路径文件夹中有多少个子文件夹。

$path = realpath(__DIR__ . '/textfiles/'); // Path to your textfiles 
$fileList = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);

foreach ($fileList as $item) {
    if ($item->isFile() && stripos($item->getPathName(), 'txt') !== false) {
        $file_contents = file_get_contents($item->getPathName());
        $file_contents = str_replace("Paul",",HHH",$file_contents);
        file_put_contents($item->getPathName(),$file_contents);
    }
}

答案 1 :(得分:1)

find /path/to/your/project -name '*.txt' -exec php yourScript.php {} \;

然后修改脚本以使用命令行参数$argv[1]作为文件路径。

答案 2 :(得分:0)

您可以使用有用的glob()内部PHP函数

$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');

因此,对于您的具体案例:

<?php
foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
    $file_contents = file_get_contents($path_to_file);
    $file_contents = str_replace("Paul",",HHH",$file_contents);
    file_put_contents($path_to_file,$file_contents);
}
?>
相关问题