搜索并替换整个目录文件内容


Search and replace entire directory file contents

我需要根据单个CSV文件的内容在单个目录中重写多个文件。

例如,CSV文件将包含如下内容:

define("LANG_BLABLA", "NEW");

在目录中的一个文件中,它将包含以下内容:

define("LANG_BLABLA", "OLD");

脚本将搜索目录以及CSV"LANG_LABLA"与旧目录LANG匹配的任何情况,它将用"NEW"更新"old"

我的问题是,如何准确地将目录中文件的内容列在1个数组中,这样我就可以轻松地搜索它们,并在必要时进行替换。

谢谢。

在目录中搜索相对容易:

<?
clearstatcache();
$folder  = "C:/web/website.com/some/folder";
$objects = scandir($folder, SCANDIR_SORT_NONE);
foreach ($objects as $obj) {
    if ($obj === '.' || $obj === '..')
        continue; // current and parent dirs
    $path = "{$folder}/{$obj}";
    if (strcasecmp(substr($path, -4), '.php') !== 0)
        continue // Not a PHP file
    if (is_link($path))
        $path = realpath($path);
    if ( ! is_file($path))
        continue; // Not a file, probably a folder
    $data = file_get_contents($path);
    if ($data === false)
        die('Some error occured...')
    // ...
    // Do your magic here
    // ...
    if (file_put_contents($path, $data) === false)
        die('Failed to write file...');
}

至于动态修改PHP文件,这可能是一个迹象,表明您需要将这些东西放入数据库或内存数据存储中。。。MySQL、SQLite、MongoDB、memcached、Redis等都应该使用。你应该使用哪个取决于你的项目的性质。

您可以使用fgetcsv将CSV文件解析为数组http://php.net/manual/en/function.fgetcsv.php

首先,如果您使用.php文件,我不建议使用此工作流。请尝试集中您的define语句,然后在一个位置对其进行更改。

但这里有一个解决方案应该适用于csv文件。它并不完整,你必须添加一些你想要的逻辑。

/**
 * Will return an array with key value coding of your csv
 * @param $defineFile Your file which contains multiple definitions e.g. define("LANG_BLABLA", "NEW");'n define("LANG_ROFL", "LOL");
 * @return array
 */
public function getKeyValueArray($defineFile)
{
    if (!file_exists($defineFile)) {
        return array();
    } else {
        $fp = @fopen($defineFile, 'r');
        $values = explode("'n", fread($fp, filesize($defineFile)));
        $newValues = array();
        foreach ($values as $val) {
            preg_match("%.*'"(.*)?'",'s+'"(.*)?'".*%", $val, $matches);
            $newValues[$matches[1]] = $matches[2];
        }
    }
}
/**
* This is s stub! You should implement the rest yourself.
*/
public function updateThings()
    {
        //Read your definition into an array
        $defs=$this->getKeyValueArray("/some/path/to/your/file");
        $scanDir="/your/desired/path/with/input/files/";
        $otherFiles= scandir($scanDir);
        foreach($otherFiles as $file){
            if($file!="." && $file!=".."){
                //read in the file definition
                $oldDefinitionArray=$this->getKeyValueArray($scanDir.$file);
                //Now you have your old file in an array e.g. array("LANG_BLABLA" => "OLD")
                //and you already have your new file in $defs
                //You now loop over both and check for each key in $defs
                //if its value equals the value in the $oldDefinitionArray.
                //You then update your csv or rewrite or do whatever you like.
            }
        }
    }