【问题标题】:how to replace a string inside files using php如何使用php替换文件中的字符串
【发布时间】:2018-05-10 12:06:21
【问题描述】:

我打算使用 php 创建一个简单的代码,它可以替换文件中的字符串,就像记事本和 ms word 中的替换函数一样,但不同之处在于它将所有匹配的字符串替换为所需的字符串,以在文件中的所有文件中进行更改文件夹任何想法如何做到这一点?

【问题讨论】:

标签: php


【解决方案1】:

您可以使用有用的glob() php 函数。

示例

<?php
   $files_in_your_folder = glob('c:\wamp\www\FindReplace\*');
   foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
    $file_contents = file_get_contents($path_to_file);
    $file_contents = str_replace("Hello","World",$file_contents);
    file_put_contents($path_to_file,$file_contents);
   }
?>

如果您的目录中有子文件夹,那么您可以使用以下代码获取文件

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

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多