[英]PHP - Splitting a string with two parameters
I'm trying to split a string received from a $_GET in PHP, but I'm stuck, as it's more than the explode() function will handle - or so I think.我正在尝试拆分从 PHP 中的 $_GET 接收到的字符串,但我被卡住了,因为它不仅仅是 explode() function 可以处理 - 或者我认为。
If the string I receive contains quotations marks (""), I want the split (by spaces) to keep the stuff in quotation marks intact.如果我收到的字符串包含引号(“”),我希望拆分(按空格)以保持引号中的内容完整。 Eg A result like 'Foo bar "Bar 2"' would be split into 1 --> Foo;例如,像 'Foo bar "Bar 2"' 这样的结果将被拆分为 1 --> Foo; 2 --> bar; 2 --> 酒吧; 3 --> Bar 2. 3 --> 小节 2。
I've looked through explode(), preg_split, and similar things, but I don't understand how to split a larger string by space, whilst keeping intact substrings that are in quotation marks.我已经查看了explode()、preg_split 和类似的东西,但我不明白如何按空格分割较大的字符串,同时保留引号中的完整子字符串。
Thanks.谢谢。
That's the definition of a CSV file with space as the delimiter.这就是以空格为分隔符的 CSV 文件的定义。 Use the CSV parsing function str_getcsv
.使用 CSV 解析 function str_getcsv
。
$str = 'Foo bar "Bar 2"';
$arr = str_getcsv($str, ' ');
print_r($arr);
Output: Output:
Array
(
[0] => Foo
[1] => bar
[2] => Bar 2
)
For PHP < 5.3, from the PHP manual's comments:对于 PHP < 5.3,来自 PHP 手册的评论:
if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
$fiveMBs = 5 * 1024 * 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
fputs($fp, $input);
rewind($fp);
$data = fgetcsv($fp, 1000, $delimiter, $enclosure); // $escape only got added in 5.3.0
fclose($fp);
return $data;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.