我正在尝试替换任何带有引号字符串的换行字符,例如
$help = '"Hi this is a string and I really want to replace
any newlines that are within that string" "There are multiple strings all within one string that all need
to have their newlines replaces"';
我都试过了。问题是我不能去掉行尾。否则,fgetcsv函数返回单个数组。它需要在引号内的行结束符/换行符
$str = str_replace(PHP_EOL, '', $str);
好的,这是我的代码。下载csv文件
<?php
$username = 'username';
$password = 'password';
$loginURL = 'http://www.example.com/login';
$contentURL = 'http://www.example.com/feedback.csv';
// Initialize the curl
$ch = curl_init();
// Pass the curl some options
curl_setopt($ch, CURLOPT_URL, $loginURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'inp-email=' . $username . '&inp-pass=' . $password);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the curl to login
$store = curl_exec($ch);
// Change the URL to the CSV and execute
curl_setopt($ch, CURLOPT_URL, $contentURL);
$content = curl_exec($ch);
// Time to sanitise, first I want to remove any newlines from customers comments
$content = ''"' .implode('"', explode(PHP_EOL, $content)) . ''"';
// Return the file contents
file_put_contents('feedback.csv', $content)
然后获取CSV文件并将其打印出来的文件…
<?php
// Function to loop through CSV and build up array
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$csvlines[] = fgetcsv($file_handle, 0, "'t");
}
fclose($file_handle);
return $csvlines;
}
// Set path to CSV file
$csvFile = 'feedback.csv';
// Read the CSV file and build array using readCSV function
$csv = readCSV($csvFile);
echo '<pre>';
foreach($csv as $line){
if(count($line) != 16){
print_r($line);
}
}
echo '</pre>';
重申一下,我想从这里开始:
$str = '"this string has no new lines" "but this one does have new
lines to strip out"';
:
$str = '"this string has no new lines" "but this one does have new lines to strip out"';
这里有一种可能的方法来解决原始问题(演示)中给出的问题:可以通过…删除双引号字符串中的所有换行符(但只有那些!)
preg_replace('#''n(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)#' , ' ', $help);
核心思想非常简单:对于每个行尾符号,我们确保它后面跟着(DQM
= "
)…
- 任意数量的非dqm符号,则…
- 正好有一个DQM,那么…
- 任意数量的非dqm,则…
- 任意数量的
single DQM - any number of non-DQM - single DQM - any number of non-DQM
组合,然后…
对于正确形成的字符串,这将导致收集位于双引号之间的结束行,如前所述。
但是,这种方法有一个警告。显然,如果该行有奇数个dqm,我们将无法纠正该行(甚至更多,在这种情况下,它将不正确地工作)。这很容易检查,只需计算字符串中的dqm。顺便说一句,对于这样的字符串,期望的行为有点不清楚:
"should "we
replace" endline here
?
理论上,它仍然可以通过使用向后查找而不是向前查找来修复一点,就像这样…
preg_replace('#(?<=^(?:[^"]*"[^"]*")*[^"]*"[^"]*)''n#' , ' ', $help);
…但是在实践中,我们不能(仍然)在PHP中使用可变长度的隐藏表达式。因此,在这种情况下,您必须求助于解析这个字符串。
如果这种考虑与您的情况无关,那么我想所示的方法可能会有所帮助。
试试这个:
$str = implode('', explode(PHP_EOL, $str));
如果不工作,尝试硬编码PHP_EOL常量:
$str = implode('', explode("'r'n", $str));
如果它仍然不工作,尝试在这里处理您的CSV文件:
foreach($csv as $line){
if(count($line) != 16){
print_r(implode('', explode("'n", $line)));
}
}