English 中文(简体)
如何删除 PHP 中双引号之间的逗号
原标题:How to remove commas between double quotes in PHP

希望这很容易。 我有一个包含 CSV 文件输出的直线阵列。 我要做的就是删除两个引用之间出现的任何逗号 。

我通过普通的表达方式 遇到麻烦。

<?php    

$csv_input =  "herp","derp","hey, get rid of these commas, man",1234 ;

$pattern =  (?<=")/,/(?=") ; //this doesn t work

$revised_input = preg_replace ( $pattern ,    , $csv_input);

echo $revised_input;

//would like revised input to echo: "herp","derp,"hey get rid of these commas man",1234

?>

非常感谢大家

最佳回答
问题回答

这是一种非常天真的做法,只有有效的逗号是那些在引号之间,除了空格之外别无他法的逗号,才有效。

<?php    

$csv_input =  "herp","derp","hey, get rid of these commas, man",1234 ;

$pattern =  /([^"]),([^"])/ ; //this doesn t work

$revised_input = preg_replace ( $pattern , "$1$2" , $csv_input);

echo $revised_input;

//ouput for this is: "herp","derp","hey get rid of these commas man",1234

应该进行更多的试验,但在这种情况下是有效的。

它可能不起作用的情况是,在字符串中没有引号的情况。

一、二、三、四- & gt; 一、二、三、四

EDIT: 纠正删除空格和相邻信件的问题。

好吧,我一直没有懒惰 写一个小的功能 做你需要的:

function clean_csv_commas($csv){
    $len = strlen($csv);
    $inside_block = FALSE;
    $out=  ;
    for($i=0;$i<$len;$i++){
        if($csv[$i]== " ){
            if($inside_block){
                $inside_block=FALSE;
            }else{
                $inside_block=TRUE;
            }
        }

        if($csv[$i]== ,  && $inside_block){
            // do nothing
        }else{
            $out.=$csv[$i];
        }

    }
    return $out;
}

你可能从错误的角度来

与其删除文本中的逗号(大概这样你就可以在逗号上拆分字符串以获得单独的元素),不如写出一些在引号上起作用的东西?

找到开首引号后, 您可以检查字符串的其余部分; 下一条引号之前的任何内容都属于此元素的一部分。 您可以在此添加一些检查来查找逃出引号, 所以比如 :

"this is a "quote""

仍然会读得正确。

但我用它来清理CSV的逗号

$csv = preg_replace (% % ” ([}]* (), ([) *)"%i, $3, $csv;

"3,120",123,345,567 gt;3120,123,345,567





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签