How to preg_replace \“ with \”" when storing in a csv file using fputcsv

谁说胖子不能爱 提交于 2019-12-08 03:58:30

问题


I'm pulling my hair out trying to do a preg_replace in php and store the results in a csv file. I want to replace \" in a string with \"" and the closest I can get to currently is \ "".

The problem is that fputcsv automatically adds a doublequote to an existing doublequote which is fine, APART FROM if the doublequote is already escaped

Here's some example code:

$code = 'document.body.innerHTML.toLowerCase().replace(/\s|\"/g, "");';   
$pattern = '(\\\")';                   
$replacement = '\\\ "';
$content[] = preg_replace($pattern, $replacement, $code);
$filename = "test.csv";
$temp_filename = "tempfile";    
$fp = fopen($tempfilename, 'w');
fputcsv($fp, $content);
fclose($fp);

In the resulting CSV file, the cell shows \ "" as demonstrated below:

"document.body.innerHTML.toLowerCase().replace(/\s|\ ""|/g, """");"

So this is nearly correct, but it needs to be \"" and not \ ""

Can anyone help me write the correct $replacement variable so that it will output \"" in the csv?
I've tried:

$replacement = '\\\""'; which produces \"""
$replacement = '\\\"'; which produces \"

So \"" is eluding me

Many many thanks if you can assist!

来源:https://stackoverflow.com/questions/26530680/how-to-preg-replace-with-when-storing-in-a-csv-file-using-fputcsv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!