Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中查找并替换多个文本文件中的字符串_Php - Fatal编程技术网

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

在PHP中查找并替换多个文本文件中的字符串,php,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); ?> 如果它只有一个文件,那

我发现这个代码:

<?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文件中查找并替换它,该怎么办

谢谢

您可以使用有用的内部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);
}
?>

这个怎么样? 它应该负责在所有.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);
    }
}

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

您可以使用php吗?或者需要使用php完成吗?
foreach(glob('/path/to/*.txt')作为$filePath){上面的代码}
可能重复的可能重复如果您在windows上,您可以打开一个命令提示符,cd到该文件夹并执行
REN**.jpg
谢谢Genesis它工作正常这是我的错误,很抱歉我在第2行出现错误(!)解析错误:语法错误,意外“:“好吧,你想用引号括起你的路径,即
非常酷的伙伴,谢谢。酷,谢谢,这真的帮了我很多改变,节省了太多的工作和时间,太棒了!虽然我还有一个疑问,我有3到4条线来代替一杆,有什么办法吗?
find /path/to/your/project -name '*.txt' -exec php yourScript.php {} \;