首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式替换双引号保持嵌套引号不变

正则表达式替换双引号保持嵌套引号不变
EN

Stack Overflow用户
提问于 2011-11-10 18:30:58
回答 3查看 202关注 0票数 0

我希望将csv记录的每个双引号替换为其他字符,比如@#@,保持内部双引号不变。

例如,考虑以下记录

代码语言:javascript
复制
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"

在这条记录中,我想用@#@替换每个字段开始和结束的双引号,这样它就变成了

代码语言:javascript
复制
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“没有变化,因为它位于已经开始的双引号中

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-11-10 19:09:53

你可以搜索

代码语言:javascript
复制
"(?=,|$)|(?<=^|,)"

并用@#@替换它。此正则表达式查找逗号(或字符串的开头/结尾)前后的引号。

因此,在PHP中:

代码语言:javascript
复制
$result = preg_replace('/"(?=,|$)|(?<=^|,)"/', '@#@', $subject);

变化

代码语言:javascript
复制
123453,"The NFL is promoting "A Crucial Catch".","Pittsburgh Steelers","NFL"

转到

代码语言:javascript
复制
123453,@#@The NFL is promoting "A Crucial Catch".@#@,@#@Pittsburgh Steelers@#@,@#@NFL@#@
票数 0
EN

Stack Overflow用户

发布于 2011-11-10 18:42:01

我增加了评论,因为你应该接受对你的问题有好答案的答案(我在那里看到了几个)……但这里有一个可能的解决方案:

代码语言:javascript
复制
<?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就可以了。

票数 1
EN

Stack Overflow用户

发布于 2011-11-10 19:08:26

为什么不遍历文件并创建一个字符串来重建this。

虽然效率不是很高,但你可以尝试……

代码语言:javascript
复制
$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 whatever
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8078119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档