mirror of
https://github.com/parsecsv/parsecsv-for-php.git
synced 2026-02-19 00:36:38 +00:00
Merge pull request #20 from Norcoen/master
Force enclosing of all columns with optional switch
This commit is contained in:
@@ -145,6 +145,15 @@ class parseCSV {
|
||||
* @var string
|
||||
*/
|
||||
public $enclosure = '"';
|
||||
|
||||
/**
|
||||
* Enclose All
|
||||
* Force enclosing all columns
|
||||
*
|
||||
* @access public
|
||||
* @var bool
|
||||
*/
|
||||
public $enclose_all = false;
|
||||
|
||||
/**
|
||||
* Conditions
|
||||
@@ -832,7 +841,7 @@ class parseCSV {
|
||||
// create heading
|
||||
if ( $this->heading && !$append && !empty($fields) ) {
|
||||
foreach( $fields as $key => $value ) {
|
||||
$entry[] = $this->_enclose_value($value);
|
||||
$entry[] = $this->_enclose_value($value, $delimiter);
|
||||
}
|
||||
|
||||
$string .= implode($delimiter, $entry).$this->linefeed;
|
||||
@@ -842,7 +851,7 @@ class parseCSV {
|
||||
// create data
|
||||
foreach( $data as $key => $row ) {
|
||||
foreach( $row as $field => $value ) {
|
||||
$entry[] = $this->_enclose_value($value);
|
||||
$entry[] = $this->_enclose_value($value, $delimiter);
|
||||
}
|
||||
|
||||
$string .= implode($delimiter, $entry).$this->linefeed;
|
||||
@@ -1045,11 +1054,14 @@ class parseCSV {
|
||||
*
|
||||
* @return Processed value
|
||||
*/
|
||||
public function _enclose_value ($value = null) {
|
||||
public function _enclose_value ($value = null, $delimiter = null) {
|
||||
if ( $delimiter === null ) {
|
||||
$delimiter = $this->delimiter;
|
||||
}
|
||||
if ( $value !== null && $value != '' ) {
|
||||
$delimiter = preg_quote($this->delimiter, '/');
|
||||
$enclosure = preg_quote($this->enclosure, '/');
|
||||
if ( preg_match("/".$delimiter."|".$enclosure."|\n|\r/i", $value) || ($value{0} == ' ' || substr($value, -1) == ' ') ) {
|
||||
$delimiter_quoted = preg_quote($delimiter, '/');
|
||||
$enclosure_quoted = preg_quote($this->enclosure, '/');
|
||||
if ( preg_match("/".$delimiter_quoted."|".$enclosure_quoted."|\n|\r/i", $value) || ($value{0} == ' ' || substr($value, -1) == ' ') || $this->enclose_all ) {
|
||||
$value = str_replace($this->enclosure, $this->enclosure.$this->enclosure, $value);
|
||||
$value = $this->enclosure.$value.$this->enclosure;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user