Php 搜索并替换整个目录文件内容
我需要根据单个CSV文件的内容在单个目录中重新写入多个文件 例如,CSV文件将包含如下内容:Php 搜索并替换整个目录文件内容,php,replace,Php,Replace,我需要根据单个CSV文件的内容在单个目录中重新写入多个文件 例如,CSV文件将包含如下内容: define("LANG_BLABLA", "NEW"); 在目录中的一个文件中,它将包含以下内容: define("LANG_BLABLA", "OLD"); 脚本将在目录中搜索CSV“LANG_BLABLA”与旧目录匹配的任何事件,它将用“NEW”更新“old” 我的问题是如何在1数组中列出目录中文件的内容,以便轻松搜索并在必要时替换 谢谢。您可以使用fgetcsv将CSV文件解析为数组,在目录
define("LANG_BLABLA", "NEW");
在目录中的一个文件中,它将包含以下内容:
define("LANG_BLABLA", "OLD");
脚本将在目录中搜索CSV“LANG_BLABLA”与旧目录匹配的任何事件,它将用“NEW”更新“old”
我的问题是如何在1数组中列出目录中文件的内容,以便轻松搜索并在必要时替换
谢谢。您可以使用
fgetcsv
将CSV文件解析为数组,在目录中搜索相对简单:
<?
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文件,我不推荐使用此工作流。尝试集中定义语句,然后在单个位置进行更改
但这里有一个解决方案,应该适用于您的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.
}
}
}
你确定这是一个CSV文件,而不是define
s的PHP文件吗?你不“列出”文件的内容。您想知道如何(递归地)列出目录中的文件,或者如何读取/替换/保存给定完整路径的文件吗?我无法想象为什么这是解决问题的好办法,而您的EAX文件无效,还有,它如何知道用什么替换什么?实际上,脚本将在目录中的每个文件中运行,并将旧的define替换为新的define(位于csv中)。解析csv不是问题,问题是解析目录中所有文件的内容,以便脚本可以查找并替换目录中存在的任何语言。如果将所有文件解析为不同的数组,则可以对它们进行比较。这是我希望避免的方法,因为目录中约有50多个文件