我想搜索一个文件并确保每一行都不以非数字字符或空格开头。 如果是这样,我想删除行并将其附加到上一行(因为它实际上是文件处理的错误......
输入:
29034985
491017
Contact us at info@
19403935
输出:
29034985
491017 Contact us at info@
19403935
我的代码这样做:
while (($data = fgetcsv('/tmp/file.tsv', 1000, "'t")) !== FALSE) {
if (is_numeric($data[0])){}
else
# do the processing here!
关于如何做到这一点的任何提示? php 有类似剪切/粘贴的功能吗?
获取所有内容并使用preg_replace替换
$data = file_get_contents('/tmp/file.tsv');
$data = preg_replace('#'n([a-zA-z].+)'n#', ' $1'n', $data);
# Write the data to a new file or to the same file
你需要做的是——
- 读取文件
- 过程数据
- 写回文件
试试这个...
$counter = 0;
$csv_data = array();
while (($data = fgetcsv('/tmp/file.tsv', 1000, "'t")) !== FALSE) {
if (is_numeric($data[0])) {
$csv_data[$counter] = $data[0];
$counter++;
} else {
$csv_data[$counter] .= ' '. $data[0];
}
}
$fp = fopen('/tmp/file.tsv', 'w');
foreach ($csv_data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);