我希望将csv记录的每个双引号替换为其他字符,比如@#@,保持内部双引号不变。
例如,考虑以下记录
123453,"The NFL is promoting the importance of annual mammogram screenings for women over 40 in the prevention of breast cancer through their "A Crucial Catch" campaign.","Pittsburgh Steelers","NFL"在这条记录中,我想用@#@替换每个字段开始和结束的双引号,这样它就变成了
123453,@#@The NFL is promoting the importance of annual mammogram screenings for women over 40 in the prevention of breast cancer through their "A Crucial Catch" campaign.@#@,@#@Pittsburgh Steelers@#@,@#@NFL@#@请注意,"A Crucial“没有变化,因为它位于已经开始的双引号中
发布于 2011-11-10 19:09:53
你可以搜索
"(?=,|$)|(?<=^|,)"并用@#@替换它。此正则表达式查找逗号(或字符串的开头/结尾)前后的引号。
因此,在PHP中:
$result = preg_replace('/"(?=,|$)|(?<=^|,)"/', '@#@', $subject);变化
123453,"The NFL is promoting "A Crucial Catch".","Pittsburgh Steelers","NFL"转到
123453,@#@The NFL is promoting "A Crucial Catch".@#@,@#@Pittsburgh Steelers@#@,@#@NFL@#@发布于 2011-11-10 18:42:01
我增加了评论,因为你应该接受对你的问题有好答案的答案(我在那里看到了几个)……但这里有一个可能的解决方案:
<?php
$orig = '123453,"The NFL is promoting the importance of annual mammogram screenings for women over 40 in the prevention of breast cancer through their "A Crucial Catch" campaign.","Pittsburgh Steelers","NFL"';
$cols = explode(',', $orig);
function replace_end_quotes($val) {
return preg_replace('#(^"|"$)#', "@#@", $val);
}
echo implode(",", array_map("replace_end_quotes", $cols));正如@socha23在评论中提到的,如果其中一个字段中有逗号,我的解决方案将不起作用。但是,如果上面的代码行实际上被格式化为有效的CSV数据,那么使用诸如str_getcsv之类的代码代替explode就可以了。
发布于 2011-11-10 19:08:26
为什么不遍历文件并创建一个字符串来重建this。
虽然效率不是很高,但你可以尝试……
$out = "";
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$arr = array();
for ($i = 0; $i < count($data); $i++) {
if (!ctype_digit($data[$i])) {
$data[$i] = '@#@' . $data[$i] . '@#@';
}
$arr[] = $data[$i];
}
$out .= implode("", $arr) . "\n";
}
fclose($handle);
}
// Write $out to file or whateverhttps://stackoverflow.com/questions/8078119
复制相似问题