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

时间:2013-07-03 14:25:29

标签: php replace

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

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

define("LANG_BLABLA", "NEW");

在目录中的一个文件中,它将包含:

define("LANG_BLABLA", "OLD");

脚本将搜索目录以及CSV“LANG_BLABLA”与旧目录LANG匹配的任何事件,它将使用“NEW”更新“OLD”

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

感谢。

3 个答案:

答案 0 :(得分:0)

您可以使用fgetcsv http://php.net/manual/en/function.fgetcsv.php

将CSV文件解析为数组

答案 1 :(得分:0)

通过目录搜索相对容易:

<?
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等都应该这样做。您应该使用哪种方式取决于项目的性质。

答案 2 :(得分:0)

首先,如果您使用.php文件,我不会推荐此工作流程。尝试集中定义语句,然后在一个位置进行更改。

但是这里有一个解决方案应该适用于您的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.
            }
        }
    }
相关问题