功能:
function parse_csv($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true){
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode($field[1]);
},
$enc
);
$lines = explode("\n",$enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', urldecode($field));
},
$fields
);
},
$lines
);
}
在PHP 5.3.x上正常工作,但在5.2.17中我收到错误:
解析错误:语法错误,第6行/inc/func.php中的意外T_FUNCTION
为什么?如何解决?
答案 0 :(得分:2)
在PHP 5.3中添加了您正在使用的function
语法。在早期版本中,您必须使用create_function
。
return array_map(
create_function('$line', '
global $delimiter, $trim_fields;
$fields = $trim_fields ? array_map(\'trim\', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace(\'!!Q!!\', \'"\', urldecode($field));
},
$fields
);',
$lines
);
答案 1 :(得分:1)
请注意,在5.3之前的PHP版本中,匿名函数/闭包不可用。但是,您仍然可以使用preg_replace_callback()
。以下是docs(示例#2)中的示例:
<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
请注意,函数next_year
以正常方式定义,然后作为字符串传递给preg_replace_callback()
。
答案 2 :(得分:0)
此问题的解决方案已在此处发布:Parse error: syntax error, unexpected T_FUNCTION line 10 ? help?
以下是在PHP 5.2或更早版本中使用preg_replace_callback的建议解决方案示例:
class My_callback {
public function __construct($s, $r) {
$this->s = $s; $this->r = $r;
}
function callback($v) { return $this->r[$v[1]]; }
}
function search_replace($s,$r,$sql) {
$e = '/('.implode('|',array_map('preg_quote', $s)).')/';
$r = array_combine($s,$r);
$c = new My_callback($s, $r);
return preg_replace_callback($e, array($c, 'callback'), $sql);
}