数据样本$string = '"word","foo","bar","foobar","barfoo"';
之前我只使用过这些:
str_replace('"','',$string)
explode(',',$string)
我删除所有引号并继续用逗号分隔它们,但后来我看到了数据样本:
$string = '"word","foo","bar","foobar","bar,foo"';
由于我依靠逗号来获取数据,因此我的代码会出错。
是否有一个php函数可以获取两个给定字符内的子字符串?或者,如果没有,有关我需要做什么功能的任何建议?
答案 0 :(得分:2)
有一个名为str_getcsv()的函数用于将CSV字符串解析为数组。如果您的字符串中有char "
(请参阅foo""bar
),其中简单的正则表达式将失败,这也适用;或者您没有引号/封闭的地方(请参阅word
)。
$string = 'word,"foo","bar","foo""bar","bar,foo"';
print_r( str_getcsv($string) );
Array
(
[0] => word
[1] => foo
[2] => bar
[3] => foo"bar
[4] => bar,foo
)
来自str_getcsv()评论(参见其他示例)区域的一个小修改示例:
function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\') {
$handle = fopen('php://memory', 'rw');
fwrite($handle, $input);
fseek($handle, 0);
$data = fgetcsv($handle, 4096, $delimiter, $enclosure, $escape);
fclose($handle);
return $data;
}
答案 1 :(得分:1)
您可以使用preg_match_all()函数:
$string = '"word","foo","bar","foobar","bar,foo"';
$pattern = '#"(.*?)"#';
preg_match_all($pattern, $string, $matches);
print_r($matches[1]);
Array
(
[0] => word
[1] => foo
[2] => bar
[3] => foobar
[4] => bar,foo
)
或者如果你想匹配所有单词:
$pattern = '#([^",]+)#';
preg_match_all($pattern, $string, $matches);
print_r($matches[1]);
Array
(
[0] => word
[1] => foo
[2] => bar
[3] => foobar
[4] => bar
[5] => foo
)
答案 2 :(得分:1)
自PHP 5.3.0以来,函数str_getcsv()可用。
对于较低版本的PHP,您可以使用以下内容:
if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = null, $eol = null) {
$temp = fopen("php://memory", "rw");
fwrite($temp, $input);
fseek($temp, 0);
$r = array();
while (( $data = fgetcsv($temp, 4096, $delimiter, $enclosure)) !== false) {
$r[] = $data;
}
fclose($temp);
return $r;
}
}
但要小心str_getcsv函数 - 如果机箱是“为这种情况测试它:
$string = '"wo"rd","fo"o","b"ar","fo"obar","ba"rfoo"';
我认为在使用str_getcsv()函数之前,必须先转义数据中的引号。
修改强>
我做了一些测试:
$str1 = '"wo"rd","foo"';
$str2 = '"wo""rd","foo"';
$str3 = '"wo\"rd","foo"';
$test_arr1 = str_getcsv($str1);
$test_arr2 = str_getcsv($str2);
$test_arr3 = str_getcsv($str3);
print_r($test_arr1);
print_r($test_arr2);
print_r($test_arr3);
输出结果为:
数组([0] =>字“[1] => foo)
数组([0] => wo“rd [1] => foo)
数组([0] => wo \“rd [1] => foo)
吨。乙
答案 3 :(得分:0)
删除开始和结束分隔符后,您可以按","
拆分。
$trimmed_string = trim($string, '\'"');
explode('","',$trimmed_string);