我正在编写一个PHP脚本,以便在大型CSV文件中进行查找和替换。我写了这个剧本:
// FIND AND REPLACE
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
$line = preg_replace ("village", "village/",fgets($source));
fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
但是我收到了这些错误,
Warning: feof() expects parameter 1 to be resource, boolean given
Warning: fgets() expects parameter 1 to be resource, boolean given
Warning: preg_replace(): Delimiter must not be alphanumeric or backslash
答案 0 :(得分:1)
awk -F'&' '{print $2}'
没有返回您认为的内容。
它可能会返回false,这通常发生在PHP无法在您提供的路径中找到该文件时。如果您某些该文件存在,则应确认执行该脚本的用户具有读取该文件的适当权限。
关于$source = fopen($sourcePath, 'r');
的第二个问题是由于没有使用分隔符引起的。第一个论点需要它们。
preg_replace()
但是,这种简单的替换不需要正则表达式。您应该使用$line = preg_replace ("/village/", "village/",fgets($source));
并且脚本应该运行得更快。
您的代码应如下所示:
str_replace()
答案 1 :(得分:0)
您没有检查fopen是否实际返回文件指针资源或错误结果。它可能返回false并抛出提供布尔值的警告。
另外,您可以使用:
$line = str_replace("village", "village/", fgets($source));